如何在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"
改變什麼預期是看跌f.name#=> 「新土地」
是的,它節省了我的時間。謝謝 –