Loop iteration - check if not

I have a function that gives several elements. I repeat them with

my_function() do |item| ... some code here ... end 

Is there a cool way to check if an iterator is not returning any items? Sort of:

 my_function() do |item| ... some code here ... else puts "No items found" end 
+4
source share
2 answers

Typically, functions that iterate over return an enumerated (e.g. array) that has been iterated. If you do this, you can check if this return value is empty:

 if my_function(){ |item| โ€ฆ }.empty? puts "nothing found!" end 

Of course, if your block is on several lines, it might make sense to write this as:

 items = my_function() do |item| # โ€ฆ end puts "Nothing found!" if items.empty? 

If it is not easy or efficient for you to create an enumerable that you repeated, you just need to change your function to return a boolean at the end indicating that you have repeated something.

+5
source

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

 result = myfunction() do |item| # some code here ... end if result.empty? puts "Something" end 
+2
source

Source: https://habr.com/ru/post/1484838/


All Articles