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.
Herein lies one of the primary differences between a block/Proc and a lambda/Method (the other primary difference would be arity). If you don't want a call to return
to exit the method, that would infer that you expect that block should be self-contained in its flow control, and be treated as an encapsulated method.
This description is essentially what a lambda is - an anonymous method. However, a standard ruby block is essentially an anonymous Proc, and takes nothing away from the flow control of the method.
As mentioned in the comments, you may be able to use next
to escape the block without returning control away from the method. 'May' because next
may just continue to the next item that the method iterator is passing to the block.
Related to this, see http://yehudakatz.com/2012/01/10/javascript-needs-blocks/ and Differences between Proc and Lambda
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments