Ruby-on-rails 映射到散列的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11505343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:41:56  来源:igfitidea点击:

Mapping to the Keys of a Hash

ruby-on-railshashmap

提问by Myxtic

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_keysback to the keys of my_hash:

于是,我尝试映射parsed_keys回的键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_keysback to the keys of my_hash?

我该如何映射parsed_keys回的键my_hash

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

我的目标是摆脱所有键末尾的“00:00:00+00”。

回答by iblue

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}

回答by woto

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

回答by Juan de Dios H.

Using iblueanswer, 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, ibluehave already posted the answer

抱歉,iblue已经发布了答案