alternative Block execution on empty Enumerable
i did not find an easy way to specify an alternative action when an iterator had nothing to iterate over.
My first try was
values.each do |v| puts v end.empty? and lambda do puts "no hit" end.call
Now that i am using rails most of the time i added a simple extension to the Enumerable and stored this within core_extensions in config/initializers.
module Enumerable def else(&block) self.respond_to?('empty?') && self.empty? ? yield : self end end
which is very useful with rails and erb too:
<% results.each do |x| %>> hit:<%=x-%>> <% end.else do %>> no hits found</li> <% end %>
if there is something simpler than that - let me know !


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago