2012-11-20 46 views
1

如何在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#=> 「新土地」

回答

0

這是一種有趣的事情,你想建立。

總結你想要兩個對象共享一個值,但只有一個被允許編輯該值,另一個只允許讀取它。

我覺得實現這個最簡單的方法是在你的情況下在Forest中實現一個新的getter,它返回land.name。通過書寫l.name = 'meow'f.name也會返回moew,因爲它保留對l的引用。

希望這會有所幫助。

+0

是的,它節省了我的時間。謝謝 –

2

在我看來,這不是OO意義上的實際繼承。如果您更改Forest,以便它保留對Land的引用,那麼您將獲得所需的行爲。

class Forest 
    attr_accessor :rain_level 

    def name 
    @land.name 
    end 

    def initialize(land, rain_level) 
    @land = land 
    @rain_level = rain_level 
    end 
end 
+0

是的,它可以實現沒有繼承。如何以繼承的方式來處理它?像父親可以設置和獲得價值和兒子只獲得價值 –

+0

繼承只是不這樣工作。如果你剃去你父親的小鬍子,那並不意味着你的上嘴脣也會被剃光。 –

+0

我明白了,我希望如果我的父親改變他的地址,那麼我的地址應該會自動改變。如果我的期望不是一種繼承,那麼請忽略它。 –