j-zhang
j-zhang

Reputation: 703

ruby: How to get the first hash item from an array if some keys of items are the same?

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

Answers (2)

Richa Sinha
Richa Sinha

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

Santhosh
Santhosh

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

Related Questions