-
-
Save addame/86722 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# alternative Block execution on empty Enumerable | |
# see : http://blog.sponagl.de/2009/1/23/alternative-block-execution-on-empty-enumerable | |
# 1. | |
ary = [] | |
ary.each do |i| | |
puts i | |
end.empty? and lambda do | |
puts "none" | |
end.call | |
# 2. add extenstion to Enumerable | |
module Enumerable | |
def else(&block) | |
self.respond_to?('empty?') && self.empty? ? yield : self | |
end | |
end | |
# us this extension in rails and erb : | |
<% results.each do |x| %> | |
<li>hit:<%=x-%></li> | |
<% end.else do %> | |
<li>no hits found</li> | |
<% end %> | |
# other suggestions | |
ary.each do |i| | |
puts i | |
end.any? or puts 'none' | |
ary.each do |i| | |
puts i | |
end.empty? and ( puts 'none' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment