感謝您查看我的問題! :)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
看起來像你在正確的軌道上。小心不小心通過'watts'這樣的參數作爲符號,你的'new(:watts)'應該是'new(watts)'。 – tadman 2014-11-03 19:59:42
引用你的對象規範:在沒有顯式返回nil的情況下,沒有這樣的事情在Ruby中的void方法。只是供參考。 – 2014-11-03 20:13:07