tags:

views:

66

answers:

2
+5  Q: 

Ruby while syntax

Does anybody why I can write this:

ruby-1.8.7-p302 > a = %w( a b c)
 => ["a", "b", "c"] 
ruby-1.8.7-p302 > while (i = a.shift) do; puts i ; end
a
b
c
 => nil 

Which looks like passing a block to while. And not:

while(i = a.shift) { puts i; }

Is it because the "do" of the while syntax is just syntaxic sugar and as nothing to do with the "do" of a block?

+5  A: 

while doesn't take a block, it's a language construct. The do is optional:

while (i = a.shift)
  puts i
end
meagar
+6  A: 
Jörg W Mittag
Brilliant. I've got to bookmark and study this one. :)
Nathan Long
Method#to_proc... I think I just fell in love with you a little bit jorg
Matt Briggs
great answer, thanks a lot Jörg!
marcgg