在方法中使用if语句时,变量不可用

时间:2014-04-03 04:21:13

标签: ruby

当我没有将if语句定义为方法时,我的代码工作正常。但是,当我这样做时,我收到的错误是

in `verify': undefined local variable or method `guess' for main:Object (NameError)

这是我正在使用的代码

def verify
  if guess > answer
    puts "Sorry! Too high."
  elsif guess < answer
    puts "Sorry! Too low."  
  else
    puts "Congratulations! You guessed it!"
  end  
end

answer = 5
puts "What is your guess?"
guess = gets.to_i
verify

1 个答案:

答案 0 :(得分:1)

您的问题是scope。在方法内部,guessanswer未定义,除非您将它们作为参数传递。

要解决此问题,可以使用:

def verify(guess, answer)
  if guess > answer
    puts "Sorry! Too high."
  elsif guess < answer
    puts "Sorry! Too low."  
  else
    puts "Congratulations! You guessed it!"
  end  
end

answer = 5
puts "What is your guess?"
guess = gets.to_i
verify(guess, answer)

请注意,方法参数不需要像这样被调用,它们可以具有任何有效名称,但是您当然必须相应地更改方法体。