按键分组哈希值,后跟值

时间:2016-11-22 15:20:35

标签: ruby

假设我有以下数据集

[ 
  {
    :name => "sam",
    :animal => "dog",
    :gender => "male"
  }, {
    :name => "max",
    :animal => "cat",
    :gender => "female"
  }, {
    :name => "joe",
    :animal => "snake",
    :gender => "male"
  }    
]

如何将散列数组分组为:

{
  :name => ["sam", "max", "joe"]
  :animal => ["dog", "cat", "snake"]
  :gender => ["male", "female", "male"]
}

我读过类似的文章,例如thisGroup array of hashes by key

但是,大多数示例都会将值作为增量计数返回,我在寻找实际的单独值。

我的尝试

keys = []
values = []

arr.each do |a|
  a.each do |k, v|
    keys << k
    #this is where it goes wrong and where I'm stuck at
    values << v
  end
end

keys = keys.uniq

我明白我出错的地方是我如何分割价值观。任何方向将不胜感激!

2 个答案:

答案 0 :(得分:4)

input.reduce { |e, acc| acc.merge(e) { |_, e1, e2| [*e2, *e1] } }
#⇒ {:name=>["sam", "max", "joe"],
#   :animal=>["dog", "cat", "snake"],
#   :gender=>["male", "female", "male"]}

答案 1 :(得分:1)

更多方法

data.each_with_object({}){ |i,r| i.each{ |k,v| (r[k] ||= []) << v } }
data.flat_map(&:to_a).each_with_object({}){ |(k,v), r| (r[k] ||= []) << v }
data.flat_map(&:to_a).group_by(&:first).inject({}){ |r, (k,v)| r[k] = v.map(&:last); r }