14

Ruby has a wealth of conditional constructs, including if/unless, while/until etc.

The while block from C:

while (condition) {
    ...
}

can be directly translated to Ruby:

while condition 
    ...
end

However, I can't seem to find a built-in equivalent in Ruby for a C-like do ... while block in which the block contents are executed at least once:

do { 
    ... 
} while (condition);

Any suggestions?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233
  • possible duplicate of [Is there a "do ... while" loop in Ruby?](http://stackoverflow.com/questions/136793/is-there-a-do-while-loop-in-ruby) – Buhake Sindi Aug 04 '13 at 17:22
  • See also: http://stackoverflow.com/questions/136793/is-there-a-do-while-loop-in-ruby – AndrewR Oct 12 '08 at 01:22

4 Answers4

31

...The best I could come up with is the loop construct with a break at the end:

loop do
    ...
    break unless condition
end
Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233
  • 4
    Yes, this is the approach that Matz recommended. see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745 – Siwei May 23 '12 at 05:24
12

You can do

i=1
begin
  ...
  i+=1 
end until 10==x

(you can also tack on a while clause to the end of begin..end)

see p 128 of Flanagan/Matz Ruby Prog'g Lang book: This is something that may be removed in releases after 1.8

Gene T
  • 5,156
  • 1
  • 24
  • 24
  • That would be the direct translation of do...while from C. It's Matz's comment that makes me a bit nervous about using this – Cristian Diaconescu Oct 10 '08 at 14:10
  • I think i should start testing in 1.9 in ubuntu and OS X, it's not hard http://blog.michaelgreenly.com/2007/12/multiple-ruby-version-on-ubuntu.html – Gene T Oct 10 '08 at 14:31
6
number=3
begin
 puts  number
 number-=1
end while number>0
haoqi
  • 71
  • 1
  • 1
-3

You can use

while condition
  ...
end
IDBD
  • 298
  • 2
  • 6
  • while condition isnt the same as do while condition. in the do while case the code gets executed at least once. – mat kelcey Oct 10 '08 at 09:22
  • 1
    The point of the question was that it's obvious how to do a `while (condition){...}` but not so obvious how to do a `do{...} while(condition)`, which runs the inside block at least once no matter what. – Cristian Diaconescu Oct 10 '08 at 14:08