Cristian Diaconescu
Cristian Diaconescu

Reputation: 35641

Does Ruby have a built-in do ... while?

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?

Upvotes: 14

Views: 10817

Answers (4)

haoqi
haoqi

Reputation: 71

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

Upvotes: 6

Gene T
Gene T

Reputation: 5176

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

Upvotes: 12

IDBD
IDBD

Reputation: 298

You can use

while condition
  ...
end

Upvotes: -3

Cristian Diaconescu
Cristian Diaconescu

Reputation: 35641

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

loop do
    ...
    break unless condition
end

Upvotes: 31

Related Questions