聋奶奶中的错误-松木-无方法 [英] errors in deaf Grandma - Pine - No Method
问题描述
完成了Def Defma的松树运动后,思想会尝试将其进一步扩展并抽象化它,以消除尽可能多的重复项.
Was completing the pine exercise for Def Grandma and thought would try and take it a little further and abstract it to remove as much duplication as possible.
希望我的逻辑不太奇怪,只是尝试将事物分为功能.但是现在如果我输入
Hope my logic with this isn't too bizzare just tried to separate things into functions. But now if I type
Bye
程序将立即退出,而无需继续执行exitPlan函数.欢迎任何建议.
The program exits immediately without proceeding to the exitPlan function. Any advice welcome.
puts 'Say something nice to Grandma.'
puts 'You may need to shout > '
speak = gets.strip
counter = 0
speaks(speak)
def speaks(speak)
if speak != 'Bye'
talk()
else
exitPlan()
end
end
def talk()
if speak == speak.downcase
puts 'Huh Speak up Sonny'
counter -= 1
else
year = rand(1930..1951)
puts 'No not Since ' + year.to_s
counter -= 1
end
if counter < 0
counter = 0 # don't want counter going below zero.
end
puts 'Say something nice to Grandma'
speaks()
end
def exitPlan()
counter += 1
unless counter == 3
puts 'Say something nice to Grandma'
speaks()
else
puts 'good night Sonny'
end
end
错误
renshaw@renshaw-TravelMate-5740G:~/Ruby$ ruby -W dGrand.rb
Say something nice to Grandma.
You may need to shout >
Bye
dGrand.rb:6:in `<main>': undefined method `speaks' for main:Object (NoMethodError)
renshaw@renshaw-TravelMate-5740G:~/Ruby$
推荐答案
您需要移动这些行
puts 'Say something nice to Grandma.'
puts 'You may need to shout > '
speak = gets.strip
counter = 0
speaks(speak)
到方法定义之后,以便在到达 speaks(speak)
行时已定义 speaks
方法.
to after your method definition so that the speaks
method has been defined when you reach the speaks(speak)
line.
那么您可能会遇到的下一个问题是
Then next problem you will probably encounter is
in `exitPlan': undefined method `+' for nil:NilClass
这是因为 counter
是一个局部变量,因此在顶级代码和其他方法之间不会共享.为此,您将需要使用全局变量,即 $ counter
,或者最好将各种方法放在类中,然后使用实例变量.
This is because counter
is a local variable so is not shared between your toplevel code and the different methods. You will need to either use a global variable i.e. $counter
for this or, better, put the various methods inside a class and then use an instance variable.
我怀疑您的代码中还有其他问题,例如您似乎只是在调用 gets.strip
来获取输入一次.但是,就将代码包装在类中而言,它不是要包装的计数器,因为您仍然需要在各种方法之间传递该计数器.这是整个语音/对话互动,所以类似
I suspect there are still some other issues in your code such as you only seem to be calling gets.strip
to get the input once. However, in terms of wrapping the code inside a class it's not the counter that you want to wrap as you would still need to pass that around between the various methods. It's the whole speak/talk interaction so something along the lines of
class Grandma
def initialize
@counter = 0
end
def speaks(speak)
..
end
def talk()
..
end
def exitPlan()
..
end
end
grandma = Grandma.new
grandma.speaks(speak)
,并使用对 @counter
这篇关于聋奶奶中的错误-松木-无方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!