-1

Say, I have two Ruby objects #<Person id:1, first:"Jane", last:"Doe"> and #<Person id:2, first:"Jane", last:"Doe"> and I would like to compare them WITHOUT considering the attribute id (or any other undesired attributes) and see if the two objects are similar.

Would be interested in learning how to use Ruby best practices to effectively ignore attributes and compare the two objects.

We would appreciate code examples for both plain Ruby object and ActiveRecord object if possible.

chadwtaylor
  • 221
  • 2
  • 10

1 Answers1

2

This might work:

def same(p1, p2)
  return false unless p1.class == p2.class
  p1_vars = p1.instance_variables.inject({}) { |h, var| h[var] = p1.instance_variable_get(var); h }
  p2_vars = p2.instance_variables.inject({}) { |h, var| h[var] = p2.instance_variable_get(var); h }
  p1_vars == p2_vars
end


class Person
  def initialize(fname, lname)
    @fname = fname
    @lname = lname
  end
end

p1 = Person.new('Jane', 'Doe')
p2 = Person.new('Jane', 'Doe')
p3 = Person.new('John', 'Doe')
p4 = 7

puts same(p1, p2) # true
puts same(p1, p3) # false
puts same(p1, p4) # false

You can use Array#reject or Array#- to subtract any undesirable attributes from instance_variables.

Amadan
  • 191,408
  • 23
  • 240
  • 301