Ruby-如何构建多值哈希? [英] Ruby-How to build a multivalued hash?
问题描述
这是我的代码段:
something_1.each do |i|
something_2.each do |j|
Data.each do |data|
date = data.attribute('TIME_PERIOD').text
value = data.attribute('OBS_VALUE').text
date_value_hash[date] = value
end
end
end
我想在一个日期中捕获所有值. date是我的哈希键,它在一个日期中可能有多个值.我如何在这里完成?当我使用此行时:
I want to capture all the values in a single date. date is the key of my hash and it may have multiple values for a single date. How can I accomplish that here? When I am using this line:
date_value_hash[date] = value
每次循环迭代时,
值都会被替换.但是,我想累积每个日期的date_value_hash中的所有值,即我想动态地构建这些值.
values are getting replaced each time the loop iterates. But, I want to accumulate all the values in my date_value_hash for each dates i.e. I want to build the values dynamically.
目前我正在得到这个:
{"1990"=>"1", "1994"=>"2", "1998"=>"0"}
但是,我想要这样的东西:
But, I want something like this:
{"1990"=>"1,2,3,4,5,6", "1994"=>"1,2,3,4,5,6", "1998"=>"1,2,3,4,5,6"}
任何人都知道我该怎么做吗?
Anyone have any idea how can I accomplish that?
推荐答案
类似
magic = Hash.new{|h,k|h[k]=[]}
magic["1990"] << "A"
magic["1990"] << "B"
magic["1994"] << "C"
magic["1998"] << "D"
magic["1994"] << "F"
之后是magic
{"1998"=>["D"], "1994"=>["C", "F"], "1990"=>["A", "B"]}
,如果您需要用逗号分隔的字符串作为值(如示例数据所示),则只需按以下方式访问它们即可:
and if you need the values as comma separated string (as indicated by your sample data), you'll just access them as
magic['1990'].join(',')
产生
"A,B"
如果以后要传递magic
并阻止其自动创建键,请按如下所示包装它
if later you want to pass magic
around and preventing it from automagically creating keys, just wrap it as follows
hash = Hash.new.update(magic)
希望有帮助!
这篇关于Ruby-如何构建多值哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!