`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 succinctly:
array.map do |x|
next x + 1 if x > 10
x - 1
end
You don't need the variable. Return value of the block is value of last expression evaluated in it. In this case, the if
.
def some_method(array)
array.map do |x|
if x > 10
x+1
else
x-1
end
end
end
Ternary operator would look nicer, I think. More expression-ish.
def some_method(array)
array.map do |x|
(x > 10) ? x+1 : x-1
end
end
If you insist on using return
, then you could use lambdas. In lambdas, return
behaves like in normal methods.
def some_method(array)
logic = ->(x) {
if x > 10
return x + 1
else
return x - 1
end
}
array.map(&logic)
end
This form is rarely seen, though. If your code is short, it surely can be rewritten as expressions. If your code is long and complicated enough to warrant multiple exit points, then probably you should try simplifying it.