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

Mapping with hash keys

I work with my_hash 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} 

Firstly, I am trying 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 

What gives me this:

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

Then I try to map parsed_keys to my_hash keys:

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

But this returns the following error:

 TypeError: can't convert String into Integer 

How can I map parsed_keys to my_hash keys?

My goal is to get rid of the “00: 00: 00 + 00” at the end of all the keys.

+6
source share
3 answers

Why don't you just do it?

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

It gives you

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

There is a new "Rails way" method for this task :)

http://api.rubyonrails.org/classes/Hash.html#method-i-transform_keys

+4
source

Using iblue's answer, you can use regexp to handle this situation, for example:

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

You can improve the template to handle various situations.

Hope this helps.

Edit:

Sorry, iblue already sent an answer

+3
source

Source: https://habr.com/ru/post/920588/


All Articles