From: Gyoung-Yoon Noh Date: 2005-05-03T11:54:45+09:00 Subject: Re: for .. in .. else? for ... end.any? or ... works similarly, but less intuitive. irb(main):003:0> for i in [1]: puts i end.any? or puts "empty" 1 => true irb(main):004:0> for i in [ ]: puts i end.any? or puts "empty" empty => nil Semantics of else in ruby's case syntax(case...when...else) and exception syntax(begin...ensure...else) also look alike python's else, so I think it is not surprising idea to add this semantic of else to 'for' and 'while'. If not good, how about modifying Array#empty? to accept block and yield when collection is empty? irb(main):001:0> class Array irb(main):002:1> def empty? irb(main):003:2> yield if size.zero? and block_given? irb(main):004:2> size.zero? irb(main):005:2> end irb(main):006:1> end => nil irb(main):007:0> for i in [1]: puts i end.empty? { puts "empty!" } 1 => false irb(main):008:0> for i in [ ]: puts i end.empty? { puts "empty!" } empty! => true On 4/23/05, Ryan Leavengood wrote: > Hal Fulton wrote: > > > >>>> Shouldn't that be "if" instead of "unless"? > > > > Actually I'm not awake enough atm to judge... but the mere fact > > that it generates discussion shows that it's ugly code that I've > > written. :) > > Come on guys, how hard is it to test? :) > > Using if is correct...to see, run this code: > > require 'erb' > > Song = Struct.new("Song", :name) > > song_list = [Song.new('Shiver'), Song.new('Free'), Song.new('Follow Me')] > > template =< > > <% if song_list.each do |song|%> > > <% end.empty? %> > > <% end %> > >
Songs
<%= song.name %>
no songs!
> END > erb = ERB.new(template) > puts "With songs:" > erb.run > song_list=[] > puts "Without songs:" > erb.run > > -- http://nohmad.sub-port.net