大佬教程收集整理的这篇文章主要介绍了Ruby – 结构和命名参数继承,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这个代码是不正确的,但它应该说明我想要了解的关于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继承使用这种类继承的命名参数?
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
以上是大佬教程为你收集整理的Ruby – 结构和命名参数继承全部内容,希望文章能够帮你解决Ruby – 结构和命名参数继承所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。