Skip to content

Instantly share code, notes, and snippets.

@addame
Forked from ianwhite/gist:79811
Created March 27, 2009 14:51
Show Gist options
  • Save addame/86722 to your computer and use it in GitHub Desktop.
Save addame/86722 to your computer and use it in GitHub Desktop.
# 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