Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Get list of different properties between objects

Helo,

I am pretty new to Ruby (using 1.8.6) and need to know whether the following functionality is available automatically and if not, which would be the best method to implement it.

I have class Car. And have two objects:

car_a and car_b

Is there any way I could do a compare and find what properties differ in one of the objects as compared to the other one?

For example,

car_a.color = 'Red'
car_a.sun_roof = true
car_a.wheels = 'Bridgestone'

car_b.color = 'Blue'
car_b.sun_roof = false
car_b.wheels = 'Bridgestone'

then doing a

car_a.compare_with(car_b)

should give me:

{:color => 'Blue', :sun_roof => 'false'}

or something to that effect?

like image 600
saurabhj Avatar asked Oct 30 '09 07:10

saurabhj


2 Answers

needs some tweaking, but here's the basic idea:

module CompareIV
  def compare(other)
    h = {}
    self.instance_variables.each do |iv|
      print iv
      a, b = self.instance_variable_get(iv), other.instance_variable_get(iv)
      h[iv] = b if a != b
    end
    return h
  end
end

class A
  include CompareIV
  attr_accessor :foo, :bar, :baz

  def initialize(foo, bar, baz)
    @foo = foo
    @bar = bar
    @baz = baz
  end
end

a = A.new(foo = 1, bar = 2, baz = 3)
b = A.new(foo = 1, bar = 3, baz = 4)

p a.compare(b)
like image 92
Martin DeMello Avatar answered Nov 14 '22 05:11

Martin DeMello


How about

class Object
  def instance_variables_compare(o)
    Hash[*self.instance_variables.map {|v| 
      self.instance_variable_get(v)==o.instance_variable_get(v) ? [] : [v,o.instance_variable_get(v)]}.flatten]
  end
end


>> car_a.instance_variables_compare(car_b)
=> {"@color"=>"Blue", "@sun_roof"=>false}
like image 2
Jonas Elfström Avatar answered Nov 14 '22 05:11

Jonas Elfström