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 !