本文介绍了未定义的方法 (NoMethodError) ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不断收到以下错误消息:
I keep getting the following error message:
text.rb:2:in `<main>': undefined method `choices' for main:Object (NoMethodError)
但我似乎无法理解为什么我的方法是未定义的":
But I can't seem to understand why my method is "undefined":
puts "Select [1] [2] [3] or [q] to quit"; users_choice = gets.chomp
choices(users_choice)
def choices (choice)
while choice != 'q'
case choice
when '1'
puts "you chose one!"
when '2'
puts "you chose two!"
when '3'
puts "you chose three!"
end
end
end
推荐答案
这是因为您在定义方法之前调用了 choices
方法.编写代码如下:
This is because you are calling method choices
, before defining it. Write the code as below:
puts "Select [1] [2] [3] or [q] to quit"
users_choice = gets.chomp
def choices (choice)
while choice != 'q'
case choice
when '1'
break puts "you chose one!"
when '2'
break puts "you chose two!"
when '3'
break puts "you chose three!"
end
end
end
choices(users_choice)
我使用了 break
来退出 while
循环.否则会造成无限循环.
I used break
, to exit from the while
loop. Otherwise it will create an infinite loop.
这篇关于未定义的方法 (NoMethodError) ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!