I have to write a Ruby method that:
-
Iterates through an array, doing Foo if one of the elements matches a certain condition.
-
If none of the array elements matched the condition, do Bar thing.
In any other language, I’d set a Boolean variable before entering the loop and toggle it if I did Foo. The value of that variable would tell me whether I needed to Bar. But that feels unRubyishly inelegant. Can anybody suggest a better way?
Edit Some really good answers, but they don’t quite work because of a detail I should have mentioned. The something that Foo does is done to the array element that matches the condition. Also, it’s guaranteed that at most one element will match the condition.
Thanks to everybody who tried to answer the question. None of you supplied an answer I found appropriate, but you all forced me to think about how you do things the Ruby way (which was the main point of this exercise!) and helped me come up with this answer:
I need to make use of the fact that iterators in Ruby are just methods. All methods return a value, and (oddly enough)
eachreturns a useful value. If the iteration completes, it returns the collection you were iterating over; if you usebreakto terminate iteration early it returnsnil(or an optional argument).So, in a Boolean context, the whole loop is
trueif it completes andfalseif you break out. Thus