我有两个文件:
answer.rb
class Answer
def decision(string)
if string == 'Richard'
puts "Hello"
else
puts "I dont know you"
end
end
end
question.rb
require './answer'
class Question < Answer
puts "What is your name?"
response = gets.chomp
puts decision("#{response}")
end
如果文件不够,如何从类Answer
访问类Question
中的方法?如果我删除了课程Answer
,那么一切正常。
答案 0 :(得分:3)
要使您的示例正常工作,您需要调用您的代码。例如,您可以使用以下代码修改Question
类:
#question.rb
require './answer'
class Question < Answer
def ask
puts "What is your name?"
response = gets.chomp
puts decision(response)
end
end
Question.new.ask
继承将是您的问题实例(即Question.new
)将继承自Answer
=&gt;它将有两种方法(在你的情况下'问'和'决定')。
答案 1 :(得分:2)
只做
puts self.new.decision(response) # no need for string interpolation.
#decision
是Answer
类的实例方法,因此它将作为类Question
的实例方法提供。现在在类中,self被设置为类本身,因此像你这样的裸方法调用将抛出错误找不到方法。因此,您必须创建类Answer
或Question
的实例,并且在该实例上您必须调用该方法。
完整代码:
class Answer
def decision(string)
if string == 'Richard'
puts "Hello"
else
puts "I dont know you"
end
end
end
class Question < Answer
puts "What is your name?"
response = gets.chomp
puts self.new.decision(response)
end
运行代码:
(arup~>Ruby)$ ruby so.rb
What is your name?
arup
I dont know you
(arup~>Ruby)$