Ruby class initialize override module initialize -
i using super
pass arguments parent initialize
method, not called default. looks like. (notice use of super
on last 2 arguments)
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
here's can it:
d = dog.new ["roll", "speak", "play dead"], "spots", true d.pet? #=> true d.get_tricks #=> ["roll", "speak", "play dead"] d.get_name #=> "spots"
it works fine, i'm wondering if there's better way this.
it not programming practice hard code fixed string
"unnamed"
value@name
. in such case, should assignnil
, , whatever modification when print it. suppose this.then
is_pet
can deduced whethername
nil
or not, redundant have instance variable. can apply!!
name
in orderis_pet
. therefore, should rid of such instance variable.you have
get_
prefixes getter methods, in ruby, better practice have same name instance variables (without atmark) getter name.
this give you:
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`)
Comments
Post a Comment