From: Robert Dober Date: 2008-06-11T19:37:52+09:00 Subject: Re: each with else On Wed, Jun 11, 2008 at 11:09 AM, Thorsten Müller wrote: > Hi all, > > that's just an idea I came up with and thought worth a discussion. > > Would it be possible to give each an else part? > > For Rails programmers it is very common to do something like this: > > In controller search for records: > > @orders = Order. find(:all) > > In view: > > <% unless @orders.empty? then %> > <% @orders.each do |order| %> > <%= output order somehow %> > <% end %> > <% else %> > output message, that there are no orders > <% end %> > > If each would have it's own else which runs if the > used array, enumerable or whatever is empty, > that code could look much nicer: > > <% @orders.each do |order| %> > <%= output order somehow %> > <% else %> > output message, that there are no orders > <% end %> > > I guess, that would be true for any other Ruby code, too. > > Please give your opinions to that idea and if you think > there would be a chance to get this implemented one day... > > Hmmm maybe you should use map than As you claimed that this is a Ruby issue I will not write Rails code here @orders.map{ |order| whatever }.empty? and puts "there are no orders" I know map with side effects is maybe a little bit counterproductive for readability and maintenance but in order to use each you have to enhance Enumerable first. module Enumerable def empty?; first > last end end @orders.each{ |order| ... }.empty? and ... but honestly would it not be better to write if @orders.empty? then else end ? BTW the implementation of Enumerable#empty? looks much more like a RCR to me. Cheers Robert -- http://ruby-smalltalk.blogspot.com/ --- As simple as possible, but not simpler. Albert Einstein