`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 endend
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 - 1end
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 endend
Ternary operator would look nicer, I think. More expression-ish.
def some_method(array) array.map do |x| (x > 10) ? x+1 : x-1 endend
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.
The return
keyword can only be used within a method(actually including Proc
). It will raise the LocalJumpError
irb(main):123:0> array = [1, 2, 3, 4, 5, 8, 9, 10, 11, 14, 15]irb(main):124:0> array.map { |n| return n }Traceback (most recent call last): 3: from (irb):124 2: from (irb):124:in `map' 1: from (irb):124:in `block in irb_binding'LocalJumpError (unexpected return)
You can use next
instead of return
.
irb(main):126:0> array.map { |n| next n }=> [1, 2, 3, 4, 5, 8, 9, 10, 11, 14, 15]