Ruby - 将数组转换为具有特定索引的哈希

时间:2013-10-01 15:38:38

标签: ruby

我有一个这样的数组:

[
  {
    'date' => '2013-09-01',
    'impressions' => 50,
    'clicks' => 20,
  },
  {
    'date' => '2013-09-02',
    'impressions' => 51,
    'clicks' => 22,
  },
]

我想从每个数组中取一个元素并使其成为哈希的索引,如下所示:

{
  '2013-09-01' => {
    'impressions' => 50,
    'clicks' => 20,
  },
  '2013-09-02' => {
    'impressions' => 51,
    'clicks' => 22,
  },
}

我意识到我可以通过暴力来做到这一点,但我认为有一些神奇的方法来帮助我。看起来splat可能是一个解决方案,但我找不到任何完全符合我想要的例子。

2 个答案:

答案 0 :(得分:0)

Hash[ a.map{ |h| [ h.delete('date') , h] } ]

答案 1 :(得分:-1)

尝试以下方法:

a = [
  {
    'date' => '2013-09-01',
    'impressions' => 50,
    'clicks' => 20,
  },
  {
    'date' => '2013-09-02',
    'impressions' => 51,
    'clicks' => 22,
  },
]

Hash[a.map{|h| [h['date'],Hash[h.to_a[1..-1]]] }]

Hash[a.map{|h| [h['date'],h.select{|k,_| k != 'date'}] }]

# => {"2013-09-01"=>{"impressions"=>50, "clicks"=>20},
 #"2013-09-02"=>{"impressions"=>51, "clicks"=>22}}