ruby程序基本设计讲解

标签 ruby loops

我想用下面的代码重写下面的代码,但是我卡住了。

def ask question
good_answer = false
while (not good_answer)
    puts question
    reply = gets.chomp.downcase

    if (reply == 'yes' or reply =='no')
        good_answer = true
        if reply == 'yes'
            answer = true
        else
            answer = false
        end
    else
        puts 'Please answer "yes" or "no"'
    end
end
answer
end

替换代码:

def ask question
    puts question
    reply = gets.chomp
    if (reply == 'yes' or reply == 'no')
        puts reply.capitalize
    else
        puts 'Please enter "yes" or "no"'
        #jump the code to like 2 ( but how?)- use while reply != empty & comment the below lines
        puts question
        reply = gets.chomp
    end
end

我想跳转到程序的主要部分,有没有goto、jump或者我可以在那个方法里面调用方法吗?

最佳答案

I want to jump to the main part of program is there any goto, jump or can I call method inside that method?

是的,它被称为循环,即您在原始代码中使用的内容。到底为什么要用 goto 替换循环?没有意义。

然而,它可以被简化。我不喜欢检查"is"或“否”,但我也没有时间重组您的程序。

def ask question
  while true
    puts(question)
    reply = gets.chomp.downcase
    if reply == 'yes' || reply == 'no'
      return reply == 'yes'
    else
      puts('Please answer "yes" or "no"')
    end 
  end
end

关于ruby程序基本设计讲解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733638/

相关文章:

javascript - 如何使用 Ruby 在 Javascript (js.erb) 中设置 url?

ruby - 从 ruby​​ 字符串中解析重复的匹配项?

linux - Loop on Unix,几何图形的基本计算器

python - Python 中不同嵌套字典的 Gen 填充率?

javascript - 为什么我不能在控制台中循环滚动浏览器窗口?

ruby-on-rails - 作业加载失败: uninitialized constant with Delayed Job and Rails 3

ruby - 如何将对象保存到文件中?

ruby - Ruby 中有没有办法打印出对象的公共(public)方法

java - 确定字符出现的最大次数并返回起始索引

php - 在 PHP 中循环数组的更好方法是什么?