views:

164

answers:

1

LOOP

This works with do:

x=0    
loop do puts x; x+=1; break if x == 100 end

but not with a semicolon:

x=0    
loop; puts x; x+=1; break if x == 100 end

UNTIL

However, this works with 'do':

until x == 100 do puts x; x+=1 end

and with a simicolon:

until x == 100; puts x; x+=1 end

With certain Ruby syntax I have a choice of using a semicolon or the 'do' keyword to delimit the end of a statement - as with the 'until' example above. But I noticed this is not possible with the Kernel.loop method at least in Ruby 1.9. Is this a recent change in the language or is the loop method just different? Is there a reason why it's like this?

+4  A: 
  • loop is a method (in Kernel) that really requires a block with do...end or { }.
  • while and until are statements (like if), and do not expect a block. The do keyword is optional, but it does not denote a block (e.g. while x == 100 { puts x; x+=1; } will fail miserably, whereas loop { puts x; x+=1; break if x == 100 } will work just fine.)

So, do means different things in the two cases. In the case of loop (and other methods) it really denotes a block; in the case of while, until etc. it is just syntactic sugar (just like then is after if.) Do not be misled.

vladr
Great answer. Thanks.