Question

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?

Was it helpful?

Solution

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

loop do
    ...
    break unless condition
end

OTHER TIPS

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

number=3
begin
 puts  number
 number-=1
end while number>0

You can use

while condition
  ...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top