Ruby-How to build a multivalued hash?

2019-05-24 00:05发布

问题:

Here is my code snippet:

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

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

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.

Currently I am getting this:

{"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?

回答1:

Like this

magic = Hash.new{|h,k|h[k]=[]}
magic["1990"] << "A"
magic["1990"] << "B"
magic["1994"] << "C"
magic["1998"] << "D"
magic["1994"] << "F"

after which magic is

{"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(',')

which yields

"A,B"

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)

Hope that helps!



回答2:

Another approach of building multi-valued hash in Ruby:

h = {}
(h[:key] ||= []) << "value 1"
(h[:key] ||= []) << "value 2"
puts h 


标签: ruby hash