将Ruby哈希转换为排序哈希数组

时间:2016-08-16 11:21:12

标签: ruby

我有以下输入:

array = [{:year=>2015, :platform_id=>2},
        {:year=>nil,  :platform_id=>2},
        {:year=>nil,  :platform_id=>4},
        {:year=>2015, :platform_id=>4}]

我需要预期的结果:

[{platform_id=>2, year=>[2015, nil]},
 {platform_id=>4, year=>[nil, 2015]}]

我的代码是:

array.inject(:merge)

但这让我得到了这个结果,这不是我想要的结果:

{:year=>2015, :platform_id=>4}

收到回复后更新如下:

在看到答案后我会进行性能测试,结果如下:

arr = [
  {:year => 2015, :platform_id => 2},
  {:year => nil, :platform_id => 2},
  {:year => nil, :platform_id => 4},
  {:year => 2015, :platform_id => 4}
]

#approach 1
x1 = Time.now.to_f
exp = arr.each_with_object({}) do |h, exp|
  exp[h[:platform_id]] ||= {:platform_id => h[:platform_id], :year => []}
  exp[h[:platform_id]][:year] << h[:year]
end.values
x2 = Time.now.to_f
p x2-x1

#approach 2
x3 = Time.now.to_f
new_data = arr.group_by { |d| d[:platform_id] }
new_arr = []
new_data.each do |k,v|
 t2 = v.map{|x| x[:year]}
 temp = {"platform_id": k, "years": t2}
 new_arr.push(temp)
end
x4 = Time.now.to_f
p x4-x3 

#approach 3
x5 = Time.now.to_f
f = arr.each_with_object({}) { |g,h|
  h.update(g[:platform_id]=>[g[:year]]) { |_,o,n| o+n } }
  #=> {2=>[2015, nil], 4=>[nil, 2015]} 

f.map { |k,v| { :platform_id=>k, :year=>v } }
x6 = Time.now.to_f
p x6-x5 

#output is:
9.059906005859375e-06
6.4373016357421875e-06
9.775161743164062e-06

1 个答案:

答案 0 :(得分:2)

arr = [
  { :year=>2015, :platform_id=>2 }, 
  { :year=>nil,  :platform_id=>2 },
  { :year=>nil,  :platform_id=>4 },
  { :year=>2015, :platform_id=>4 }
]

arr.each_with_object({}) { |g,h|
  h.update(g[:platform_id]=>[g[:year]]) { |_,o,n| o+n } }.
    map { |k,v| { :platform_id=>k, :year=>v } }
    #=> [{:platform_id=>2, :year=>[2015, nil]},
    #    {:platform_id=>4, :year=>[nil, 2015]}] 

这两个步骤如下。

f = arr.each_with_object({}) { |g,h|
  h.update(g[:platform_id]=>[g[:year]]) { |_,o,n| o+n } }
  #=> {2=>[2015, nil], 4=>[nil, 2015]} 

f.map { |k,v| { :platform_id=>k, :year=>v } }
  #=> [{:platform_id=>2, :year=>[2015, nil]},
  #    {:platform_id=>4, :year=>[nil, 2015]}] 

第一步使用Hash#update(aka merge!)的形式,它使用一个块(此处为{ |_,o,n| o+n })来计算两个哈希值中合并的键值。