首页 > 解决方案 > 返回子类常量数组的不同元素

问题描述

我有一个Parent定义为常量数组的类COLUMNS

class Parent
  COLUMNS = [
    { column: 'type', type: 'String' }
  ]
end

还有一个Child具有相同常量名称的类称为COLUMNS

class Child < Parent
  COLUMNS = [
    { column: 'type', type: 'String' },
    { column: 'user', type: 'String' },
    { column: 'password', type: 'String' }
  ]
end

如何Child从类常量数组中仅获取类常量数组的非相同元素Parent。IE,

# Expected output

[
  { column: 'user', type: 'String' },
  { column: 'password', type: 'String' }
]

标签: ruby-on-railsruby

解决方案


class Parent
  COLUMNS = [
    { column: 'type', type: 'String' }
  ]

  def self.fields
    COLUMNS
  end
end

class Child < Parent
  COLUMNS = [
    { column: 'type', type: 'String' },
    { column: 'user', type: 'String' },
    { column: 'password', type: 'String' }
  ]

  def self.fields
    COLUMNS - super
  end

  fields
end

输出:

=> [{:column=>"user", :type=>"String"}, {:column=>"password", :type=>"String"}] 

推荐阅读