Ruby - extracting the unique values per key from an array of hashes

前端 未结 2 1401
深忆病人
深忆病人 2020-12-31 18:32

From a hash like the below one, need to extract the unique values per key

array_of_hashes = [ {\'a\' => 1, \'b\' => 2 , \'c\' => 3} , 
                      


        
2条回答
  •  感动是毒
    2020-12-31 18:38

    This is more generic:

    options = {}
    distinct_keys = array_of_hashes.map(&:keys).flatten.uniq
    distinct_keys.each do |k|
      options[k] = array_of_hashes.map {|o| o[k]}.uniq
    end
    

提交回复
热议问题