简体   繁体   English

比较数组中多个哈希值

[英]Compare values from multiple hashes within an array

I know for-loops should be avoided and i guess the better way to iterate through an array is instead of doing 我知道应该避免for循环,我想遍历数组的更好方法是

for i in 0..array.size-1 do
  puts array[i]
end

do

array.each{ |x| 
  puts x
}

But what if i had an array of hashes like 但是如果我有一系列的哈希

array = [{:value0 => 1, :value1 => 0}, {:value0 => 2, :value1 => 1}, {:value0 => 1, :value1 => 2}]

and wanted to check if :value0 is unique in all hashes.. intuitively I would do something like 并想检查:value0在所有哈希中是否唯一..直观上我会做类似的事情

for i in 0..array.size-1 do
  _value_buffer = array[i][:value0]
  for j in i+1..array.size-1 do
    if _value_buffer == array[j][:value0]
      puts "whatever"
    end
  end
end

Is there a better way to do this? 有一个更好的方法吗?

Why not just get all the values in question and see if they're unique? 为什么不仅仅获取所有有疑问的值,看看它们是否唯一?

!array.map { |h| h[:value0] }.uniq!

( uniq! returns nil when there are no duplicates) (当没有重复项时, uniq!返回nil

就像安德鲁·马歇尔(Andrew Marshall)所说的那样,您可以使用uniq !,但使用的方法更为简洁:

!array.uniq!{|a| a[:value0]}

Here is how I would do it: 这是我的方法:

2.0.0p195 :001 > array = [{:value0 => 1, :value2 => 0}, {:value0 => 2, :value2 => 1}, {:value0 => 1, :value2 => 2}]
 => [{:value0=>1, :value2=>0}, {:value0=>2, :value2=>1}, {:value0=>1, :value2=>2}] 
2.0.0p195 :002 > val0 = array.map { |hash| hash[:value0] }
 => [1, 2, 1] 
2.0.0p195 :003 > puts val0.uniq == val0
false
 => nil

I would collect the values of :value0 and then compare them to the array of unique values. 我将收集:value0的值,然后将它们与唯一值数组进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM