I use return when I scroll through the list, and I want to exit the function if any member of the list matches the criteria. I could accomplish this with a single statement, for example:
list.select{|k| k.meets_criteria}.length == 0
in some situations but
list.each{|k| return false if k.meets_criteria}
- also one line - in my opinion, 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 it's a test to make sure it's safe to continue working with the rest of the method, the first example will have to handle it differently.
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 am sure that this can be achieved in one line, without return , but from the top of my head I do not see how to do this.
But now this is a rather flexible line of code that can be called by any list of logical methods and a list of objects that implement these methods.
EDIT
It should be noted that I assume that this line is inside the method, not the block.
But this is basically a stylistic choice, I think that in most situations, you can and possibly avoid using return .
philosodad Jan 05 2018-11-11T00: 00Z
source share