Home > Enterprise >  Remove from array of hashes [closed]
Remove from array of hashes [closed]

Time:10-06

I have a parent class that contains a constant COLUMNS and child class with same constant with custom columns. In child class how to remove parent class columns

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

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

should return

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

CodePudding user response:

Just substract one from the other:

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

COLUMNS = CLIENT_COLUMNS - PARENT_COLUMNS
#=> [{:column=>"user", :type=>"String"}, {:column=>"password", :type=>"String"}]

CodePudding user response:

Input

PARENT = [
  { column: 'type', type: 'String' }
]

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

Code

CHILD.delete_if {|h|PARENT.include?(h)}


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

Output

CodePudding user response:

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

Output:

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