I am creating a user class which has a first name and last name.
class User
attr_accessor :first_name, :last_name
end
Then, I created a teacher class to teach knowledge.
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
Now, finally, I created student class to access functionality of user and teacher classes with some added functions.
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
What I would like Student class #learn to do is take the instance variable @string1 and push that to knowledge array. Somehow, it's not working as I tink it should.
Also, I have this bin file, where I have a student and a teacher. So, if I try to see knowledge array, It doesn't respond!
#!/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
I will really appreciate if anyone can help me to find what's wrong with my code!
You are referencing the instance variable @string1
(evaluating to nil
) instead of the parameter string1
.
Try this:
def learn(string1)
@knowledge.push(string1)
end
Also you seem to be trying to "share" an instance variable. But, by definition, an instance variable belongs to just one instance of an object. But that's not a problem - your teach()
method already returns some knowledge, which you can then use in your learn()
method.