`return` in Ruby Array#map

Sergio’s answer is very good, but it’s worth pointing out that there is a keyword that works the way you wanted return to work: next.

array.map do |x|
  if x > 10
    next x + 1
  else
    next x - 1
  end
end

This isn’t a very good use of next because, as Sergio pointed out, you don’t need anything there. However, you can use next to express it more explicitly:

array.map do |x|
  next x + 1 if x > 10
  x - 1
end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)