4

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
Tisho
  • 8,320
  • 6
  • 44
  • 52
  • possible duplicate of [Ruby best practice : if not empty each do else in one operator](http://stackoverflow.com/questions/16860310/ruby-best-practice-if-not-empty-each-do-else-in-one-operator) – sawa Jun 06 '13 at 13:49
  • 3
    @sawa Though that question is pretty heavily steeped in performing the action within Haml, where certain constructs cannot by used. – Phrogz Jun 06 '13 at 14:00

2 Answers2

5

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.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • This is the right way to go. And it is the same as my answer to [this question](http://stackoverflow.com/questions/16860310). I wonder why I got two downvotes whereas this answer got three upvotes (including one from me). – sawa Jun 06 '13 at 13:52
2

You can assign the return of the iteration to a variable, and then compare it to anything.

result = myfunction() do |item|
  # some code here ...
end
if result.empty?
  puts "Something"
end
MurifoX
  • 14,991
  • 3
  • 36
  • 60