基类继承

时间:2014-02-12 15:03:41

标签: ruby class

我有两个文件:

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,那么一切正常。

2 个答案:

答案 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.

#decisionAnswer类的实例方法,因此它将作为类Question的实例方法提供。现在在类中,self被设置为本身,因此像你这样的裸方法调用将抛出错误找不到方法。因此,您必须创建类AnswerQuestion的实例,并且在该实例上您必须调用该方法。

完整代码:

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)$