AmanKing

do-while in RubyControl PanelChange LogBrowse PagesSearch?

do-while in Ruby

Ever wondered how you could get a do-while in Ruby?

 i=0
 loop {
   puts i
   break unless (i+=1)<0
 }

The above is equivalent to the following Java do-while:

 int i=0;
 do {
   System.out.println(i);
 } while(++i < 0);


Another way allowed in Ruby is:

 i=0
 begin
   puts i
 end while (i+=1)<0

However, Matz recommends not to use the above because

 begin; <some code...> end while <some condition> 

evaluates differently from

 <some code...> while <some condition> 

The former acts as do-while and the latter acts as a while.

Refer to Ruby Weekly News.

Tags: technology:ruby, technology:coding Last modified 22:07 Wed, 17 Jan 2007 by Main. Accessed 768 times Children What Links Here share Share Except where expressly noted, this work is licensed under a Creative Commons License.