开发者

Ruby transforming a hash, combining multiple values

Consider I have an array of hashes (which is my map/reduced output from MongoDB) which look similar to the following:

[ 
  {"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},
  ...
]

But I don't want all of those time related keys and values, I'd like to combine them into a date object for each object, also would it not be more efficient to be using symbols as my 开发者_如何学运维keys rather than strings?

[
  {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},
  ...
]

Any help on this would be really awesome. Thanks!


The straight forward way is probably as good as you're going to get, if you're array is a then:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜