是否有一个"回到顶部"在Ruby?

时间:2014-08-28 01:02:21

标签: ruby

我在ruby编程中有点像菜鸟。我的问题是,如果在ruby中有类似锚点或goto的东西,那么我可以在Ifs中创建循环......是否有类似的东西?

示例:

anchorX
gets variable
if variable == "option one"
   puts "you choose right"
else
   puts "you choose wrong! DO IT AGAIN!"
go to anchorX

3 个答案:

答案 0 :(得分:3)

不,Ruby没有goto。请尝试循环:

loop {
    input = gets.chomp
    if input == "option one"
        puts "you choose right"
        break
    else
        puts "you choose wrong! DO IT AGAIN!"
    end
}

或者,另一种方法(可以说更具可读性):

input = gets.chomp
until input == "option one"
   puts "you choose wrong! DO IT AGAIN!"
   input = gets.chomp
end
puts "you choose right"

答案 1 :(得分:0)

为什么要将goto用于如此微不足道的事情?

使用while循环。 ruby的while语法是:

while [condition] do
   (put your code here)
end

例如:

gets variable
while variable != "option one" do
    puts "you choose wrong!"
    gets variable
puts "you choose right"

答案 2 :(得分:0)

除了循环语句,您还可以使用retry语句重复整个开始/结束块。

begin
    input = gets.chomp
    if input == "option one"
        puts "you choose right"
    else
        puts "you choose wrong! DO IT AGAIN!"
        raise
    end
rescue 
    retry
end