Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop iteration - check if no items are yielded

Tags:

ruby

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
like image 798
Tisho Avatar asked Mar 24 '23 16:03

Tisho


1 Answers

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.

like image 76
Phrogz Avatar answered Apr 25 '23 04:04

Phrogz