루비 : 객체간에 다른 속성 목록을 가져옵니다
-
22-07-2019 - |
문제
헬리콥터,
나는 루비를 처음 접했고 (1.8.6 사용) 다음 기능을 자동으로 사용할 수 있는지 여부와 그렇지 않은 경우이를 구현하기에 가장 적합한 방법이 될 것입니다.
나는 수업 자동차가 있습니다. 그리고 두 개의 개체가 있습니다.
car_a and car_b
비교할 수있는 방법이 있습니까? 다른 객체와 비교하여 객체 중 하나에서 어떤 속성이 다른지 찾으십니까?
예를 들어,
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'
그런 다음 a
car_a.compare_with(car_b)
나에게 주어야한다 :
{:color => 'Blue', :sun_roof => 'false'}
아니면 그 효과에 뭔가?
해결책
약간의 조정이 필요하지만 여기에 기본 아이디어가 있습니다.
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)
다른 팁
어때
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}
속성의 차이를 곧바로 얻을 수 있는지 확실하지 않습니다. 그러나 주변의 작업은 .eql을 시도하는 것입니까? 두 개체의 연산자
#for example,
car_a.eql?(car_b)
#could test whether car_a and car_b have the same color, sunroof and wheels
#need to override this method in the Car class to be meaningful,otherwise it's the same as ==
차이가 있으면 객체 클래스의 TO_ARRAY 메소드를 사용할 수 있습니다.
car_a.to_a
car_b.to_a
이제 차이를 위해 2 개의 배열을 비교하는 것은 쉬운 일입니다.
테스트가 아니라
(car_a | car_b ) - ( car_a & car_b )
또는 그와 비슷한 것이 속성의 차이를 제공해야합니다.
HTH
나는 같은 문제가 있었고 당신의 솔루션 중 일부를보고 있었지만 루비는 이것을 해결할 방법이 있어야한다고 생각했습니다. 나는 ActiveModel :: Dirty를 발견했습니다. 매력처럼 작동합니다.
http://api.rubyonrails.org/classes/activemodel/dirty.html#method-i-changes
제휴하지 않습니다 StackOverflow