`return` in Ruby Array#map

Automatico picture Automatico · Sep 6, 2016 · Viewed 13.5k times · Source

I have a method where I would like to decide what to return within a map function. I am aware that this can be done with assigning a variable, but this is how I though I could do it;

def some_method(array)
    array.map do |x|
      if x > 10
         return x+1 #or whatever
      else
         return x-1
      end
    end
end

This does not work as I expect because the first time return is hit, it returns from the method, and not in the map function, similar to how the return is used in javascript's map function.

Is there a way to achieve my desired syntax? Or do I need to assign this to a variable, and leave it hanging at the end like this:

def some_method(array)
    array.map do |x|
      returnme = x-1
      if x > 10
         returnme = x+1 #or whatever
      end
      returnme
    end
end

Answer

Jordan Running picture Jordan Running · Sep 6, 2016

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 succinctly:

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