0

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!

1
  • 1
    it's just a map, I don't see the problem... show at least what you've tried. Commented Oct 6, 2011 at 7:52

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

+1, but why destroy "a"? b = a.map ... Also, it may look better this way: DateTime.new(*h.values_at('year', 'month', 'date', 'hour', 'minute'))
@tokland: How about pancakes instead of b? I got the impression that he wanted to replace it. I'd probably go with values_at if I had the keys in an array (and then we'd have a double splat!) or if I needed a longer variable name than h but it doesn't make that much difference here.
I would have gone for "cupcakes", but "pancakes" is also good ;-) I think that following FP principles -even if you pay a bit of memory/cpu penalty in a language like Ruby- is worth it. I think it's good pedagogy to mention it, some programmers haven't heard about FP and keep updating variables inplace for no good reason.
@tokland: I'm a Fargo fan so it is always pancakes. I'm not one to complain about reasonable criticism.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.