Ruby类关系:如何使用另一个类中的方法和对象?
感谢您查看我的问题!:) 我对Ruby编程相当陌生,我很难理解如何在代码中实现类,也很难让它们相互继承方法和变量 我有一个等级灯泡,看起来像这样:Ruby类关系:如何使用另一个类中的方法和对象?,ruby,class,inheritance,methods,Ruby,Class,Inheritance,Methods,感谢您查看我的问题!:) 我对Ruby编程相当陌生,我很难理解如何在代码中实现类,也很难让它们相互继承方法和变量 我有一个等级灯泡,看起来像这样: class LightBulb def initialize( watts, on ) @watts = watts @on = on end # accessor methods def watts @watts end def on @on end # other method
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( )
…我正在尝试创建一个有灯泡的类灯,并在不同的时间使用它。我知道在继承树图上,它们应该彼此相邻(即Lightbull--Lamp,而不是Lightbull,在面向对象的术语中,这可以通过委托这些方法来实现:
class Lamp
def turnon
@lightbulb.turnof
end
def turnoff
@lightbulb.turnoff
end
end
这些传递方法在Ruby代码中非常常见,您需要将一个对象包装到另一个对象中
如果你更喜欢冒险,还有一个模块
从面向对象的设计角度来看,我更关心这里的责任链。例如,当灯泡处于关闭/打开状态时,灯本身充当“控制器”当然。你是对的,这不是继承,而是封装。你在这里肯定不需要继承。你在组成这些对象,一盏灯有一个灯泡。你很接近,你真正需要做的就是调用你缺少的灯泡上的方法:
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
的值。如果您感兴趣,.看起来您走的方向正确。如果不小心将watts
之类的参数作为符号传递,请小心e您的new(:watts)
应该是new(watts)
。参考您的对象规范:Ruby中没有没有不显式返回nil的void方法。仅供参考。感谢您的帮助,我想我现在理解了这些概念;我对稍微接近正确答案感到更有信心。:)非常感谢你,Nick,我不知道如何在我的initialize方法中引用另一个类,但是你完全清除了它!我对符号也很陌生,所以再次感谢您解释我应该如何传递变量。:)
class Lamp
def turnon
@lightbulb.turnof
end
def turnoff
@lightbulb.turnoff
end
end
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