How to implement inheritance in ruby for the following?
class Land
attr_accessor :name, :area
def initialize(name, area)
@name = name
@area = area
end
end
class Forest < Land
attr_accessor :rain_level
attr_reader :name
def name=(_name)
begin
raise "could not set name"
rescue Exception => e
puts e.message
end
end
def initialize(land, rain_level)
@name = land.name
@rain_level = rain_level
end
end
l = Land.new("land", 2300)
f = Forest.new(l, 400)
puts f.name # => "land"
suppose when i change name for land l, then it should change for sub class also
l.name ="new land"
puts f.name # => "land"
what expected is puts f.name # => “new land”
This is kind of an interesting thing you want to build.
Summarizing you want to have two objects that share a value but only one is allowed to edit the value, the other one is only allowed to read it.
I think the easiest way to implement this is in your case to implement a new getter in Forest which returns
land.name. By writingl.name = 'meow'willf.namereturnmoewtoo because it holds a reference tol.Hope this helps.