Reputation: 703
For example:
array = [
{"a"=>1, "b"=>2, "c"=>3},
{"a"=>1, "b"=>2, "c"=>4},
{"a"=>2, "b"=>1, "c"=>5},
{"a"=>2, "b"=>1, "c"=>6}
]
If key a
and key b
are both the same in the hash, I want to get the first item. Such as:
array = [
{"a"=>1, "b"=>2, "c"=>3},
{"a"=>2, "b"=>1, "c"=>5}
]
Is there any way to distinct the hash key and get the first one?
Upvotes: 1
Views: 83
Reputation: 1456
You can try the following:
arr=[]
array.each do|h|
arr.push h if !arr.any?{|hash|hash["a"]==h["a"] && hash["b"]==h["b"]}
end
p arr
Upvotes: 0
Reputation: 29124
You can use Array#uniq, with a block
array.uniq {|h| [h['a'],h['b']] }
# => [{"a"=>1, "b"=>2, "c"=>3}, {"a"=>2, "b"=>1, "c"=>5}]
Upvotes: 7