I use return when I'm going through a list, and I want to exit the function if any member of the list meets a criteria. I could accomplish this with a single statement like:
list.select{|k| k.meets_criteria}.length == 0
in some situations, but
list.each{|k| return false if k.meets_criteria}
is one line too--with, to my mind, some added flexibility. For example, the first example assumes that this is the only line in the method, and that we want to return from this point no matter what. But if this is a test to see whether it is safe to proceed with the rest of the method, the first example will need to handle that in a different way.
EDIT:
To add some flexibility, consider the following line of code:
list_of_method_names_as_symbols.each{|k| list_of_objects.each{|j| return k if j.send(k)}}
I'm sure this can be accomplished, in one line, without return
, but off the top of my head I don't see how.
But this is now a fairly flexible line of code that can be called with any list of boolean methods and a list of objects that implement those methods.
EDIT
It should be noted that I'm assuming this line is inside a method, not a block.
But this is mostly a stylistic choice, I think that in most situations, you can and possibly should avoid using return
.