【发布时间】:2017-08-12 02:41:13
【问题描述】:
我正在创建一个具有名字和姓氏的用户类。
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
如果有人能帮我找出我的代码有什么问题,我将不胜感激!
【问题讨论】:
标签: ruby-on-rails arrays ruby inheritance instance-variables