将一个子类的实例变量用于另一个子类

时间:2017-03-20 17:23:13

标签: ruby-on-rails arrays ruby inheritance instance-variables

我正在创建一个具有名字和姓氏的用户类。

class User

  attr_accessor :first_name, :last_name

end

然后,我创建了一个教授知识的教师课程。

require_relative "./user.rb"

class Teacher < User

  attr_accessor :string1

  def initialize
    @string1 = string1
  end

  KNOWLEDGE = ["a String is a type of data in Ruby", "programming is hard, but it's worth it", "javascript async web request", "Ruby method call definition", "object oriented dog cat class instance", "class method class variable instance method instance variable", "programming computers hacking learning terminal", "bash Ruby rvm update certs"]


  def teach
    @string1 = KNOWLEDGE.sample
  end

end

现在,最后,我创建了学生课程,以访问具有一些附加功能的用户和教师课程的功能。

require_relative "./user.rb"
require_relative "./teacher.rb"

class Student  < User

  attr_accessor :knowledge

  def initialize
    @knowledge = []
  end

  def learn(string1)
    @knowledge.push(@string1)
  end


end

我想要学生类#learn要做的是获取实例变量@ string1并将其推送到知识数组。不知何故,它不起作用,因为我应该叮叮当当。

另外,我有这个bin文件,我有一个学生和一个老师。所以,如果我试图看到知识数组,它就没有回应!

#!/usr/bin/env ruby
require_relative "../lib/user.rb"
require_relative "../lib/teacher.rb"
require_relative "../lib/student.rb"

hima = Student.new
hima.first_name = "Hima"
hima.last_name = "Chhag"

pooja = User.new
pooja.first_name = "Pooja"
pooja.last_name = "Jeckson"

trushal = Teacher.new
trushal.first_name = "Trushal"
trushal.last_name = "Chitalia"


some_knowledge = trushal.teach

hima.learn(some_knowledge)

puts "Hima just learned this important knowledge: '#{hima.knowledge[0]}' from Trushal"

some_knowledge = trushal.teach

hima.learn(some_knowledge)

puts "Hima just learned this important knowledge: '#{hima.knowledge[1]}' from Trushal"

hima.knowledge

如果有人能帮助我找到我的代码有什么问题,我将非常感激!

1 个答案:

答案 0 :(得分:0)

您正在引用实例变量@string1(评估为nil)而不是参数string1

试试这个:

def learn(string1)
  @knowledge.push(string1)
end

此外,您似乎正在尝试“共享”实例变量。但是,根据定义,实例变量只属于对象的一个​​实例。但这不是问题 - 您的teach()方法已经返回了一些知识,您可以在learn()方法中使用这些知识。