0

I have the following array:

array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]

I want to convert it into 1 big hash but keep all of the values, so I want it to look like the following:

{"a" => [2, nil], "b" => [3, nil], "c" => [2]}

I can get close doing array.inject({}) {|s, h| s.merge(h)}}, but it overwrites the values.

2
  • 1
    wouldn't it make more sense to have "c"=> [2] in the hash? Commented Jul 2, 2013 at 21:01
  • yea that works as well Commented Jul 2, 2013 at 21:02

2 Answers 2

2
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
a = array.each_with_object(Hash.new([])) do |h1,h|
  h1.each{|k,v| h[k] = h[k] + [v]}
end
a # => {"a"=>[2, nil], "b"=>[3, nil], "c"=>[2]}
Sign up to request clarification or add additional context in comments.

Comments

0
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
res = {}

array.each do |hash|
  hash.each do |k, v|
    res[k] ||= []
    res[k] << v
  end
end

2 Comments

You can get rid of the res[k] ||= [] line if you change res = {} to res = Hash.new []
thanks @naomik but I like it this way. There are some strange stuff going on when you use Hash with default values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.