Ruby有内置的功能吗?

时间:2022-04-07 12:55:46

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

Ruby有大量的条件结构,包括if/unless、while/until等。

The while block from C:

C的while块:

while (condition) {
    ...
}

can be directly translated to Ruby:

可以直接翻译成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:

然而,在Ruby中,我似乎找不到类似c的功能。而块中至少执行一次块内容:

do { 
    ... 
} while (condition);

Any suggestions?

有什么建议吗?

4 个解决方案

#1


30  

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

…我能想到的最好的方法是循环结构,最后有一个间断:

loop do
    ...
    break unless condition
end

#2


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)

(你也可以在begin. end结尾加上while从句)

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

参阅Flanagan/Matz Ruby Prog'g Lang book的p128:这是在1.8之后可能被删除的东西。

#3


6  

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

#4


-3  

You can use

您可以使用

while condition
  ...
end

#1


30  

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

…我能想到的最好的方法是循环结构,最后有一个间断:

loop do
    ...
    break unless condition
end

#2


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)

(你也可以在begin. end结尾加上while从句)

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

参阅Flanagan/Matz Ruby Prog'g Lang book的p128:这是在1.8之后可能被删除的东西。

#3


6  

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

#4


-3  

You can use

您可以使用

while condition
  ...
end