开发者

comparing array of hashes

开发者 https://www.devze.com 2023-02-19 04:40 出处:网络
I have array of hashes [{\"a\" => 1, \"b\" => 2}, {\"a\"=> 3, \"b\" => 4}, {\"a\" => 5, \"b开发者_如何转开发\" => 6}]. Now I need to compare all the hashes with each other, ie, compa

I have array of hashes [{"a" => 1, "b" => 2}, {"a"=> 3, "b" => 4}, {"a" => 5, "b开发者_如何转开发" => 6}]. Now I need to compare all the hashes with each other, ie, compare 1st hash with 2nd and 3rd hash, and 2nd with 3rd hash. If anybody has any idea, please let me know!


Rails has class Hash with diff method which returns the hash difference

{"a" => 1, "b" => 2}.diff("a"=> 3, "b" => 4) # { "a" => 1, "b" => 2 }

Look also at merge method, it could be useful in your case


Try this in your rails console :

irb(main):001:0> array = [{"a" => 1, "b" => 2}, {"a"=> 3, "b" => 4}, {"a" => 5, "b" => 6}]
irb(main):002:0> 0.upto(array.length-2) do |index|
irb(main):003:1* (index+1).upto(array.length-1) do |index2|
irb(main):004:2* puts "array[#{index}][a]-array[#{index2}][a] is : #{array[index]["a"]-array[index2]["a"]}"
irb(main):005:2> puts "array[#{index}][b]-array[#{index2}][b] is : #{array[index]["b"]-array[index2]["b"]}"
irb(main):006:2> end
irb(main):007:1> end
array[0][a]-array[1][a] is : -2
array[0][b]-array[1][b] is : -2
array[0][a]-array[2][a] is : -4
array[0][b]-array[2][b] is : -4
array[1][a]-array[2][a] is : -2
array[1][b]-array[2][b] is : -2
=> 0

And that's how you can compare them. I've used minus (-), you may want to use AND (&) then for that you have to put "&" symbol at the place of "-" else you can do whatever operation you wants to perform on it... :)


rails has a nice little hash.diff method that can be easily ported into Ruby

0

精彩评论

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