Home > OS >  Return Nonidentical elements of a Child class Constant array [closed]
Return Nonidentical elements of a Child class Constant array [closed]

Time:10-07

I have a Parent class that has a Constant Array defined as COLUMNS

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

And a Child class with the same Constant name called COLUMNS

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

How to fetch only the Nonidentical elements of a Child class Constant Array from that of Parent class Constant Array. i.e.,

# Expected output

[
  { 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:

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"}] 

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

  • Related