如何在 ruby 中为以下实现继承?
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"
假设当我更改土地 l 的名称时,它也应该更改为子类
l.name ="new land"
puts f.name # => "land"
预期的是 puts f.name # => "new land"