【发布时间】:2014-12-30 13:41:18
【问题描述】:
感谢您查看我的问题! :)
我对 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( )
...我正在尝试创建一个具有灯泡的类 Lamp 并在不同时间使用它。我知道在继承树图上,它们应该彼此相邻(即 LightBulb--Lamp,而不是 LightBulb
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
如何在 Lamp 类中使用 LightBulb 类的 turnon() 和 turnoff() 方法以及灯泡对象?
到目前为止,这是我对 Lamp 的了解,但我确信其中大部分是不正确的:
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)。 -
参考您的对象规范:在没有显式返回 nil 的情况下,Ruby 中没有 void 方法之类的东西。仅供参考。
标签: ruby class inheritance methods