我super
用来将参数传递给父initialize
方法,默认情况下不会调用它。这就是它的样子。(注意super
最后两个参数的使用)
module Pet
def initialize name, is_pet
@is_pet = is_pet
if is_pet
@name = name
else
@name = "Unnamed"
end
end
def pet?
return @is_pet
end
def get_name
return @name
end
end
class Dog
include Pet
def initialize tricks, name, is_pet
@tricks = tricks
super name, is_pet
end
def get_tricks
return @tricks
end
end
这是我可以做的:
d = Dog.new ["roll", "speak", "play dead"], "Spots", true
d.pet? #=> true
d.get_tricks #=> ["roll", "speak", "play dead"]
d.get_name #=> "Spots"
它工作正常,但我只是想知道是否有更好的方法可以做到这一点。
硬编码固定字符串(如"Unnamed"
的值)不是一种好的编程习惯@name
。在这种情况下,您应该分配nil
,并在打印时对其进行任何修改。假设您这样做。
然后is_pet
可以从是否推断name
是nil
与否,所以这是多余的有,作为一个实例变量。你可以简单地适用!!
于name
为了得到is_pet
。因此,您应该摆脱这种实例变量。
您可以将get_
前缀用作getter方法,但是在Ruby中,与getter名称具有与实例变量相同的名称(不带atmark)是一种更好的做法。
这将为您提供:
module Pet
attr_reader :name
def initialize name; @name = name end
end
class Dog
include Pet
attr_reader :tricks
def initialize tricks, name
@tricks = tricks
super(name)
end
end
d = Dog.new ["roll", "speak", "play dead"], "Spots"
d.tricks #=> ["roll", "speak", "play dead"]
d.name #=> "Spots"
!!d.name #=> true (= `is_pet`)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句