DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

How To Display Message When Collection Is Empty

05.03.2005
| 1954 views |
  • submit to reddit
        
>> for i in [1]
>>   puts i
>> end.any? or puts "empty!"
1
=> true
>> for i in [ ]
>>   puts i
>> end.any? or puts "empty!"
empty!
=> nil

short circuit evaluation is not intutitive? try this.

>> class Array
>>   alias :__empty? :empty?
>>   def empty?
>>     yield if __empty? and block_given?
>>     __empty?
>>   end
>> end
=> nil
>> for i in [1]
>>   puts i
>> end.empty? { puts "empty!" }
1
=> false
>> for i in [ ]
>>   puts i
>> end.empty? { puts "empty!" }
empty!
=> true