Ruby – 结构和命名参数继承
发布时间:2020-12-16 20:28:07 所属栏目:百科 来源:网络整理
导读:这个问题是严格的结构性行为,所以请不要“为什么在广泛的运动世界你是这样做的?” 这个代码是不正确的,但它应该说明我想要了解的关于Ruby的结构: class Person Struct.new(:name,:last_name)endclass ReligiousPerson Person(:religion)endclass Political
|
这个问题是严格的结构性行为,所以请不要“为什么在广泛的运动世界你是这样做的?”
这个代码是不正确的,但它应该说明我想要了解的关于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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
