这个问题完全是关于 Struct 行为的,所以请不要问“为什么在广泛的体育世界中你要那样做?”
此代码不正确,但它应该说明我试图了解的有关 Ruby Structs 的内容:
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 定义类继承。但是,当然,当您尝试初始化 ReligiousPerson 或 PoliticalPerson 时,Ruby 会变得脾气暴躁。因此,鉴于此说明性代码,如何使用这种使用 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', 'bill', 'Zoroastrianism')
p political_person = PoliticalPerson.new('frankie', 'frank', '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', 'jack')
p pious_person = ReligiousPerson.new('billy', 'bill', 'Zoroastrianism')
p political_person = PoliticalPerson.new('frankie', 'frank', 'Connecticut for Lieberman')
工作正常!
您还可以将#derived_struct 添加到 Struct:
class Struct
def self.derived_struct( *args )
Struct.new(*self.members, *args)
end
end
关于Ruby - 结构和命名参数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6891258/