这个问题是严格的结构性行为,所以请不要“为什么在广泛的运动世界你是这样做的?”
这个代码是不正确的,但它应该说明我想要了解的关于Ruby的结构:
class Person < Struct.new(:name,:last_name) end class ReligIoUsPerson < Person(:religion) end class PoliticalPerson < Person(:political_affiliation) end ### Main ### person = Person.new('jackie','jack') pIoUs_person = ReligIoUsPerson.new('billy','bill','Zoroastrianism') political_person = PoliticalPerson.new('frankie','frank','Connecticut for Lieberman')
正如你所看到的,尝试使用Structs来定义一个类继承.但是,当您尝试初始化宗教人士或政治人物时,Ruby变得笨拙.所以给出这个说明性的代码,怎么可能使用Structs继承使用这种类继承的命名参数?
解决方法
您可以定义新的Structs,基于Person:
class Person < Struct.new(:name,:last_name) end class ReligIoUsPerson < Struct.new(*Person.members,:religion) end class PoliticalPerson < Struct.new(*Person.members,:political_affiliation) end ### Main ### person = Person.new('jackie','jack') p pIoUs_person = ReligIoUsPerson.new('billy','Zoroastrianism') p political_person = PoliticalPerson.new('frankie','Connecticut for Lieberman')
结果:
#<struct ReligIoUsPerson name="billy",last_name="bill",religion="Zoroastrianism"> #<struct PoliticalPerson name="frankie",last_name="frank",political_affiliation="Connecticut for Lieberman">
立即发布我的答案后,我有一个想法:
class Person < Struct.new(:name,:last_name) def self.derived_struct( *args ) Struct.new(*self.members,*args) end end class ReligIoUsPerson < Person.derived_struct(:religion) end class PoliticalPerson < Person.derived_struct(:political_affiliation) end ### Main ### person = Person.new('jackie','Connecticut for Lieberman')
工作正常!
您还可以将#derived_struct添加到Struct:
class Struct def self.derived_struct( *args ) Struct.new(*self.members,*args) end end