Search code examples
rubyintrospection

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?


Solution

  • 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)