Ruby - 结构和命名参数继承

标签 ruby inheritance struct

这个问题完全是关于 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/

相关文章:

c++ - 程序接收信号 SIGSEGV 段错误

有两个参数的 Ruby 方法(一个有默认值)只接受一个

ruby-on-rails - 我如何检查 Ruby on Rails 中的当前时间是否在今晚 9 点到早上 9 点(明天)之间

java - 如何在没有instanceof或类型转换的情况下以OOP方式防止继承破坏所有依赖关系?

C 结构节点

c - 为什么这个赋值在函数之外不起作用?

ruby-on-rails - 如何在 Mac OS X 上卸载 Ruby on Rails?

ruby-on-rails - has_many :messages where user is recipient or author in one query

java - 如何重写构造函数

grails - Grails/GORM 中的继承和约束问题