I've noticed that if I use the keyword return
inside of a block, the entire method returns. I find it confusing that in ruby, you can optionally use the return
keyword - it's like: "So what is this thing returning, if anything? Did the developer intend this method to return something?" So I like using return
even inside blocks, for example:
def my_method
items = [ 1, 2, 3 ]
items_times_ten = items.collect { |o|
#multiple
#lines
#of
#code ...
return o * 10 # Ruby exits the method at this point.
}
return items_times_ten #This is never reached.
end
I understand why I don't need to return from the block, but if my block was more intricate, it would seem to help with clarity. My question is, why in the world would Ruby assume that I want to return control out two levels?
If my assumption is incorrect, please correct me. I just want to understand the reasons that control is handled in this way.