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

Using instance variable of one sub class in to another sub class

我正在创建一个用户 class,它有名字和姓氏。

class User

  attr_accessor :first_name, :last_name

end

然后,我创建了一个老师class来传授知识

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

现在,我终于创建了学生 class 来访问用户和教师 classes 的功能并增加了一些功能。

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

我希望 Student class #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

如果有人能帮我找出我的代码有什么问题,我将不胜感激!

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

试试这个:

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

您似乎也在尝试 "share" 一个实例变量。但是,根据定义,一个实例变量只属于一个对象的一个​​实例。但这不是问题 - 您的 teach() 方法已经 returns 一些知识,然后您可以在 learn() 方法中使用这些知识。