Search code examples
ruby-on-railsrubyhashmap

Mapping the keys of a Hash


I am working with a hash called my_hash:

{
  "2011-02-01 00:00:00+00" => 816,
  "2011-01-01 00:00:00+00" => 58,
  "2011-03-01 00:00:00+00" => 241
}

My aim is to get rid of the “00:00:00+00” at the end of all the keys, resulting in this hash:

{
  "2011-02-01" => 816,
  "2011-01-01" => 58,
  "2011-03-01" => 241
}

What I tried

First, I try to parse all the keys in my_hash (which are timestamps).

my_hash.keys.sort.each do |key|
  parsed_keys << Date.parse(key).to_s
end

Which gives me this:

["2011-01-01", "2011-02-01", "2011-03-01"]

Then, I try to map parsed_keys back to the keys of my_hash:

Hash[my_hash.map {|k,v| [parsed_keys[k], v]}]

But that returns the following error:

TypeError: can't convert String into Integer

How can I map parsed_keys back to the keys of my_hash?


Solution

  • Why don't you just do this?

    my_hash.map{|k,v| {k.gsub(" 00:00:00+00","") => v}}.reduce(:merge)
    

    This gives you

    {"2011-02-01"=>816, "2011-01-01"=>58, "2011-03-01"=>241}