我正在使用名为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_hash中的所有键(有时).
my_hash.keys.sort.each do |key| parsed_keys << Date.parse(key).to_s end
哪个给了我这个:
["2011-01-01","2011-02-01","2011-03-01"]
然后,我尝试将parsed_keys映射回my_hash的键:
Hash[my_hash.map {|k,v| [parsed_keys[k],v]}]
但是返回以下错误:
TypeError: can't convert String into Integer
如何将parsed_keys映射回my_hash的键?
我的目标是在所有键的末尾摆脱“00:00:00 00”.
解决方法
你为什么不这样做?
my_hash.map{|k,v| {k.gsub(" 00:00:00+00","") => v}}.reduce(:merge)
这给了你
{"2011-02-01"=>816,"2011-01-01"=>58,"2011-03-01"=>241}