2014-11-03 49 views
3

感謝您查看我的問題! :)Ruby類關係:如何使用另一個類的方法和對象?

我是相當新的在Ruby編程,我無法理解如何在我的代碼中實現類,並讓他們從彼此繼承方法和變量。

我有一個類燈泡,它看起來像這樣:

class LightBulb 
    def initialize(watts, on) 
    @watts = watts 
    @on = on 
    end 

    # accessor methods 
    def watts 
    @watts 
    end 

    def on 
    @on 
    end 

    # other methods 
    def turnon 
    @on = true 
    end 

    def turnoff 
    @on = false 
    end 

    def to_s 
    "#{@watts}-#{@on}" 
    end 
end 

以及與工程類驅動程序:

# a lit, 30-watt bulb 

b = LightBulb.new(30, false) 
b.turnon() 
Bulb  

# a 50-watt bulb 

fiftyWatt = LightBulb.new(50, false) 
fiftyWatt.turnoff() 

...,我試圖建立一個這種燈具有一個LightBulb,並在不同的時間使用它。我知道在繼承樹圖上,它們應該是彼此相鄰的(即LightBulb - Lamp,而不是LightBulb < --Lamp),所以我不知道是否應該使用繼承運算符<。 這裏是基本的結構,我需要的燈類:

Lamp (string make, string model, double cost, int watts) 
-- accessors 
string make() 
string model() 
-- methods 
void turnon() # turn on the bulb 
void turnoff() # turn off the bulb 
--class members 
string make 
string model 
double cost 
LightBulb bulb 

我如何將能夠使用導通()和關斷()從燈泡類的方法,以及燈泡的對象,在燈類?

下面是我對燈,到目前爲止,但我敢肯定大部分是不正確的:

class Lamp 
    attr_accessor :watts 
    def initialize(make, model, cost, watts) 
     @make = make 
     @model = model 
     @cost = cost 
     @watts = LightBulb.new(:watts) 
    end 

    def make 
     @make 
    end 

    def model 
     @model 
    end 

    def cost 
     @cost 
    end 
end 
+2

看起來像你在正確的軌道上。小心不小心通過'watts'這樣的參數作爲符號,你的'new(:watts)'應該是'new(watts)'。 – tadman 2014-11-03 19:59:42

+0

引用你的對象規範:在沒有顯式返回nil的情況下,沒有這樣的事情在Ruby中的void方法。只是供參考。 – 2014-11-03 20:13:07

回答

3

你絕對不需要在這裏繼承。您正在撰寫這些對象,燈具有LightBulb。你靠近,和你真正需要做的是叫你錯失了燈泡的方法:

class Lamp 

    def initialize(make, model, cost, watts) 
    @make = make 
    @model = model 
    @cost = cost 
    @bulb = LightBulb.new(watts, false) 
    end 

    # ... 

    def turnon 
    @bulb.turnon 
    end 

    def turnoff 
    @bulb.turnoff 
    end 

end 

因此,我改變@watts@bulb,而放棄了:watts象徵,你真的需要通過傳入的值爲watts。如果您有興趣,請撥打here is some more information on symbols

+0

非常感謝Nick,我很困惑我在初始化方法中如何引用另一個類,但你完全清除了它!而且我對符號也很陌生,所以再次感謝您解釋我應該如何傳遞變量。 :) – paulalucai 2014-11-04 00:19:54

2

在面向對象的術語,這是可以通過委派這些方法來進行:

class Lamp 
    def turnon 
    @lightbulb.turnof 
    end 

    def turnoff 
    @lightbulb.turnoff 
    end 
end 

這些傳遞方法在Ruby代碼中很常見,您需要將一個對象包裝在另一個對象中。如果你感覺更冒險,還有Forwardable模塊。

從面向對象的設計角度來看,我更關心這裏的責任鏈。例如,當燈泡處於關閉/打開狀態時,燈本身就起到了「控制器」的作用。你說得對,這不是繼承的情況,而是封裝。

+1

感謝您的幫助,我認爲我現在對這些概念有所瞭解;而且我對於稍微接近正確的答案感到更加自信。 :) – paulalucai 2014-11-04 00:18:42

相關問題