Ruby:获取对象之间不同属性的列表

sau*_*bhj 7 ruby introspection

直升机,

我是Ruby的新手(使用1.8.6)并且需要知道以下功能是否可以自动使用,如果没有,这将是实现它的最佳方法.

我上课了.并有两个对象:

car_a and car_b
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以进行比较并找出其中一个对象与另一个对象相比有哪些属性?

例如,

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'
Run Code Online (Sandbox Code Playgroud)

然后做一个

car_a.compare_with(car_b)
Run Code Online (Sandbox Code Playgroud)

应该给我:

{:color => 'Blue', :sun_roof => 'false'}
Run Code Online (Sandbox Code Playgroud)

或者那种效果?

Mar*_*llo 7

需要一些调整,但这是基本的想法:

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)
Run Code Online (Sandbox Code Playgroud)