开发者

How to check if any of the Objects have the same data for the same field?

开发者 https://www.devze.com 2023-03-22 20:41 出处:网络
Is there a sweet irb line of code that could check is any of the Object\'s have the same data in their 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号