Aravind
Aravind

Reputation: 1401

Add two hashes with same key in ruby

I have a hash like this:

a = {:start=>"Tue, 27 Jan 2015 13:00:00 +0000", :end=>"Tue, 27 Jan 2015 13:30:00 +0000", :title=>"2015-01-27T13:00:00+00:00 to 2015-01-27T13:30:00+00:00"}

and another hash like

b = {:start=>Tue, 27 Jan 2015 13:30:00 +0000, :end=>Tue, 27 Jan 2015 14:00:00 +0000, :title=>"2015-01-27T13:30:00+00:00 to 2015-01-27T14:00:00+00:00"}

I want to merge these two into

c = {{:start=>"Tue, 27 Jan 2015 13:00:00 +0000", :end=>"Tue, 27 Jan 2015 13:30:00 +0000", :title=>"2015-01-27T13:00:00+00:00 to 2015-01-27T13:30:00+00:00"},{:start=>Tue, 27 Jan 2015 13:30:00 +0000, :end=>Tue, 27 Jan 2015 14:00:00 +0000, title=>"2015-01-27T13:30:00+00:00 to 2015-01-27T14:00:00+00:00"}}

I tried the following:

c = a.merge(b)

and also

a.merge!(b)

This gave back only one value and

c = a+b 

gave errors.

How to do this?

Upvotes: 0

Views: 379

Answers (1)

Satya
Satya

Reputation: 4478

Its syntactically incorrect even for JSON, I believe. You want an array of hashes, by turning the outer {} into []. Better: c = [a,b].to_json

Upvotes: 5

Related Questions