Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping to 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}

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

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 ?

My aim is to get rid of the "00:00:00+00" at end of all the keys.

like image 934
Myxtic Avatar asked Jul 16 '12 13:07

Myxtic


1 Answers

Another alternative could be:

  1. map
  2. return converted two elements array [converted_key, converted_value]
  3. convert back to a hash
irb(main):001:0> {a: 1, b: 2}.map{|k,v| [k.to_s, v.to_s]}.to_h               
=> {"a"=>"1", "b"=>"2"}   
like image 196
Marcos Bellucci Avatar answered Sep 27 '22 17:09

Marcos Bellucci