You do not need a variable. The return value of a block is the value of the last expression evaluated in it. In this case, if .
def some_method(array) array.map do |x| if x > 10 x+1 else x-1 end end end
A ternary operator would look better, 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 , you can 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 rare. If your code is short, it can be rewritten as expressions. If your code is long and complex enough to guarantee multiple exit points, then you should probably try to simplify it.
source share