I have a function, which yields few items. I'm iterating them using
my_function() do |item|
... some code here ...
end
Is there a cool way to check if the iterator doesn't return any items? Something like:
my_function() do |item|
... some code here ...
else
puts "No items found"
end
Usually functions that iterate return the enumerable (e.g. array) that was iterated. If you do this, you can test if this return value is empty:
if my_function(){ |item| … }.empty?
puts "nothing found!"
end
Of course, if your block is on multiple lines it may make more sense to write this as:
items = my_function() do |item|
# …
end
puts "Nothing found!" if items.empty?
If it's not easy or efficient for you to create an enumerable that you iterated, then you simply need to modify your function to return a boolean at the end indicating if you iterated anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With