How to check if any of the Objects have the same data for the same field?
Is there a sweet irb
line of code that could check is any of the Object
's have the same data in their field?
For example, could I see if any of the Object
's have the same email? Alternatively, check and 开发者_JAVA技巧see if any of the objects are not unique?
You could try it this way:
Create a hash with all instance variables as key-value pairs and then compare the hashes:
Assuming you have two objects a and b:
hash_a = a.instance_variables.inject({}){|res,v| res[v] = a.instance_variable_get(v); res }
hash_b = b.instance_variables.inject({}){|res,v| res[v] = b.instance_variable_get(v); res }
if hash_a == hash_b
puts "equal"
else
puts "not equal"
end
Edit:
If you are talking about Rails Models then you need this:
if a.attributes == b.attributes
puts "equal"
end
精彩评论