简体   繁体   中英

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 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

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)

就像安德鲁·马歇尔(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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