for ... end.any? or ... works similarly, but less intuitive.

<snip>
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
</snip>

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?

<snip>
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
</snip>

On 4/23/05, Ryan Leavengood <mrcode / netrox.net> 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 =<<END
>  <table>
>    <tr><th>Songs</th></tr>
>    <% if song_list.each do |song|%>
>      <tr><td><%= song.name %></td></tr>
>      <% end.empty? %>
>      <tr><td>no songs!</td></tr>
>    <% end %>
>    </tr>
>  </table>
> END
> erb = ERB.new(template)
> puts "With songs:"
> erb.run
> song_list=[]
> puts "Without songs:"
> erb.run
> 
> 


-- 
http://nohmad.sub-port.net