简体   繁体   English

映射到哈希的键

[英]Mapping to the Keys of a Hash

I am working with a hash called my_hash : 我正在使用名为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中的所有键(有时候)。

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 : 于是,我尝试映射回parsed_keysmy_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 ? 我该如何映射parsed_keysmy_hash的钥匙?

My aim is to get rid of the "00:00:00+00" at end of all the keys. 我的目标是在所有键的末尾摆脱“00:00:00 + 00”。

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}

There is a new "Rails way" methods for this task :) 这项任务有一种新的“Rails方式”方法:)

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

Using iblue answer, you could use a regexp to handle this situation, for example: 使用iblue答案,您可以使用正则表达式来处理这种情况,例如:

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

You could improve the pattern to handle different situations. 您可以改进模式以处理不同的情况。

Hope it helps. 希望能帮助到你。

Edit: 编辑:

Sorry, iblue have already posted the answer 对不起, iblue已经发布了答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM