views:

2346

answers:

5

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?

+4  A: 

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

loop do
    ...
    break unless condition
end
Cristi Diaconescu
A: 

You can use

while condition
  ...
end
IDBD
while condition isnt the same as do while condition.in the do while case the code gets executed at least once.
matpalm
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.
Cristi Diaconescu
+5  A: 

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
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
Cristi Diaconescu
I think i should start testing in 1.9 in ubuntu and OS X, it's not hardhttp://blog.michaelgreenly.com/2007/12/multiple-ruby-version-on-ubuntu.html
Gene T
A: 
number=3
begin
 puts  number
 number-=1
end while number>0
haoqi