变量在if / else语句中不匹配

时间:2014-02-22 01:52:28

标签: ruby if-statement

我正在创建一个让你解决随机数学问题的方法。代码如下:

def subtraction()
   puts "Your goal is to solve the math problem."
   # Asks if user is ready
   ready()

   a = rand(0..5)
   b = rand(0..5)
   c = a - b
   puts "what is #{a} - #{b}?"



   prompt; next_move = gets.chomp


     if next_move == c
       puts "Lucky guess!"
       water()       
    elsif next_move != c
      puts "The answer was: #{c}"
      dead("You suck at life")
    else 
      dead("You didn't type anything")
    end
end

我一直在尝试运行此操作,并不断获得elsif选项。即使我用puts语句检查我的变量也匹配。我没有朝着我想要的方向前进。我做错了什么?

1 个答案:

答案 0 :(得分:3)

更改

 next_move = gets.chomp

next_move = gets.chomp.to_i # gets.to_i will work also.

Kernel#gets将为您提供字符串,如果您的工作不是像此示例那样使用字符串对象,则需要根据需要将其转换为适当的对象。根据行c = a - b,我非常确定,您需要将string对象从stdin更改为整数对象。所以你必须使用String#to_i