ruby程序基本设计说明

时间:2012-01-04 20:36:15

标签: 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或者我可以在该方法中调用方法吗?

4 个答案:

答案 0 :(得分:2)

  

我想跳到程序的主要部分是否有任何goto,jump或者我可以在该方法中调用方法吗?

是的,它被称为循环,即您在原始代码中使用的内容。为什么在世界上你想要用goto替换循环?毫无意义。

然而,它可以简化。我不喜欢检查'是'或者没有',但我也没有时间重组您的计划。

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

答案 1 :(得分:1)

即使有goto语句,您也不应该使用它。它不仅形式不好,而且会给维护者带来各种麻烦,因为你的程序最终难以理解。

更好的方法是为您的问题和有效答案定义适当的结构,然后简单地迭代这些结构,将结果收集到您稍后可以使用的结构中:

# Auto-flush output buffer
STDOUT.sync = true

questions = [
  [ 'Is this a good question?', 'yes', 'no' ],
  [ 'Is the sky blue?', 'yes', 'no' ],
  [ 'Do hamsters fly?', 'no', 'yes' ]
]

answers_given = [ ]

questions.each do |question, *answers|
  print question + ' '

  while (true)
    answer = gets

    answer.chomp!

    if (answers.include?(answer))
      puts "Thanks!"

      answers_given << (answer == answers.first)

      break
    end

    puts "You must answer one of #{answers.join(', ')}!"
    print question + ' '
  end
end

questions.each_with_index do |(question, *answers), i|
  puts "#{question} #{answers_given[i]}"
end

答案 2 :(得分:1)

您可以尝试这样的事情:

def ask_question  
  puts('Please answer "yes" or "no"') until (reply = gets.chomp.downcase) =~ /^(yes|no)$/

  return reply == 'yes'
end

答案 3 :(得分:-1)

def ask question  
puts question  
reply = gets.chomp.downcase  
if (reply == 'yes' or reply == 'no')  
    puts reply.capitalize  
else  
    puts 'Please enter "yes" or "no"'  
    ask question # this does the looping of loop
end
end  

谢谢,对不起,我上次没有从剪贴板上复制好。