`return` in Ruby Array # map

I have a method where I would like to decide what to return to map functions. I know that this can be done with variable assignment, but this is how 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 hits, it returns from the method and not to the map function, similar to the way the return is used in the javascript display function.

Is there a way to achieve the desired syntax? Or I need to assign this to a variable and leave it 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 
+6
source share
2 answers

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.

+12
source

Sergio's answer is very good, but it's worth noting that there is a keyword that works the way you wanted return : next .

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

This is not very well used next , because, as Sergio noted, you do not need anything. However, you can use next to express it more briefly:

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

All Articles