Ruby转换哈希,组合多个值

时间:2011-10-06 07:43:39

标签: ruby

考虑我有一个哈希数组(这是我的MongoDB的map /简化输出),它看起来类似于以下内容:

[ 
  {"minute"=>30.0, "hour"=>15.0, "date"=>5.0, "month"=>9.0, "year"=>2011.0, "type"=>10.0, "count"=>299.0},
  {"minute"=>0.0, "hour"=>16.0, "date"=>5.0, "month"=>9.0, "year"=>2011.0, "type"=>10.0, "count"=>477.0},
  ...
]

但我不想要所有那些与时间相关的键和值,我想将它们组合成每个对象的日期对象,使用符号作为我的键也不会更有效率而不是字符串?

[
  {timestamp: DateTime.new(2011.0, 9.0, 5.0, 15.0, 30.0), count: 299, type: 10},
  {timestamp: DateTime.new(2011.0, 9.0, 5.0, 16.0, 0.0), count: 477, type: 10},
  ...
]

对此的任何帮助都会非常棒。谢谢!

1 个答案:

答案 0 :(得分:2)

如果您的数组是a那么,那么直截了当的方式可能就像您将获得的一样好:

pancakes = a.map do |h|
    {
        :timestamp => DateTime.new(h['year'], h['month'], h['date'], h['hour'], h['minute']),
        :count     => h['count'].to_i,
        :type      => h['type'].to_i
    }
end
相关问题