JP Silvashy
JP Silvashy

Reputation: 48535

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!

Upvotes: 0

Views: 296

Answers (1)

mu is too short
mu is too short

Reputation: 434765

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

Upvotes: 2

Related Questions