不确定.include方法-需要帮助调试

时间:2019-07-12 22:33:40

标签: ruby

我正在用Ruby创建一个简单的Magic-8 Ball程序。我想确保用户提出问题,所以我在条件语句中使用了.include方法。我发誓我没有正确使用它,但是在终端中运行程序时出现错误。

根据我在Google上找到的内容,我尝试以不同的方式使用.include方法,但似乎没有任何效果。

    puts "Please ask the Magic 8 Ball a YES/NO question:"
    question = gets.chomp

    puts "Please enter your name:"
    name = gets.chomp

    magic_8 = rand(6)

    if question.include? "?" && magic_8 == 0
      puts "\nIt is certain, #{name}."
    elsif question.include? "?" && magic_8 == 1
      puts "\nI'm not so sure, #{name}."
    elsif question.include? "?" && magic_8 == 2
      puts "\nI'll have to get back to you on that, #{name}."
    elsif question.include? "?" && magic_8 == 3
      puts "\nIt's not likely, #{name}."
    elsif question.include? "?" && magic_8 == 4
      puts "\nAbsolutely, #{name}!"
    elsif question.include? "?" && magic_8 == 5
      puts "\nDefinitely not, #{name}."
    else
      puts "Please enter a valid YES/NO question, #{name}."
    end

我希望程序只要用户输入包含“?”的问题就可以随机输出条件语句。

2 个答案:

答案 0 :(得分:1)

/Users/schwern/tmp/test.rb:9:in `include?': no implicit conversion of false into String (TypeError)
    from /Users/schwern/tmp/test.rb:9:in `<main>'

问题是优先。通常,您可以不用在方法参数上加上括号,但是这次不可以。

question.include? "?" && magic_8 == 0

您期望这样:

question.include?("?") && magic_8 == 0

但是由于&&的优先级很高,因此Ruby对此进行了解释。

question.include?("?" && magic_8 == 0)

"?" && magic_8 == 0false,所以question.include?(false)毫无意义。

因此,您需要明确说明您的父母。 question.include?("?") && magic_8 == 0

我们还可以通过一次又一次地检查question.include?("?")来完全避免该问题。可以将其放到自己的if / else块中。

if question.include?("?")
  case magic_8
  when 0
    puts "\nIt is certain, #{name}."
  when 1
    puts "\nI'm not so sure, #{name}."
  when 2
    puts "\nI'll have to get back to you on that, #{name}."
  when 3
    puts "\nIt's not likely, #{name}."
  when 4
    puts "\nAbsolutely, #{name}!"
  when 5
    puts "\nDefinitely not, #{name}."
  end
else
  puts "Please enter a valid YES/NO question, #{name}."
end

我们只需要检查他们是否问过一次问题。然后在if内,我们可以使用case/when(就像if / elsif一样更方便)来检查8球。

答案 1 :(得分:0)

对方法调用的参数使用括号。您会把没有它们的解释器弄糊涂。

if question.include?("?") && magic_8 == 0
  puts "\nIt is certain, #{name}."
elsif question.include?("?") && magic_8 == 1
  puts "\nI'm not so sure, #{name}."
elsif question.include?("?") && magic_8 == 2
  puts "\nI'll have to get back to you on that, #{name}."
elsif question.include?("?") && magic_8 == 3
  puts "\nIt's not likely, #{name}."
elsif question.include?("?") && magic_8 == 4
  puts "\nAbsolutely, #{name}!"
elsif question.include?("?") && magic_8 == 5
  puts "\nDefinitely not, #{name}."
else
  puts "Please enter a valid YES/NO question, #{name}."
end

更多here