itx
itx

Reputation: 1399

Merge hash with another hash

I have two hash like

h1 = {
  DateTime.new(2015, 7, 1),in_time_zone => 0,
  DateTime.new(2015, 7, 2).in_time_zone => 10, 
  DateTime.new(2015, 7, 4).in_time_zone => 20, 
  DateTime.new(2015, 7, 5).in_time_zone => 5
}

h2 = {
  DateTime.new(2015, 7, 1).in_time_zone => 0,
  DateTime.new(2015, 7, 2).in_time_zone => 0,
  DateTime.new(2015, 7, 3).in_time_zone => 0
}

I want to merge h1 and h2, don't merge if key already exist, so that will result look like (datetime format with time zone shortened for readability)

result
#=> {
#     Wed, 01 Jul 2015 01:00:00 EST +01:00 => 0,
#     Thu, 02 Jul 2015 01:00:00 EST +01:00 => 10,
#     Fri, 03 Jul 2015 01:00:00 EST +01:00 => 0,
#     Sat, 04 Jul 2015 01:00:00 EST +01:00 => 20,
#     Sun, 05 Jul 2015 01:00:00 EST +01:00 => 5
#   }

I have tried with h1.merge(h2) and h2.merge(h1) but it can be put key and value of h2 to h1.

Upvotes: 0

Views: 354

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

arr = []
h = h1.merge(h2)
h.each{|k, v| arr.include?(v) ? h.delete(k) : arr << v }

#=> {#<DateTime: 2015-07-01T00:00:00+00:00 ((2457205j,0s,0n),+0s,2299161j)>=>0,
     #<DateTime: 2015-07-04T00:00:00+00:00 ((2457208j,0s,0n),+0s,2299161j)>=>20,
     #<DateTime: 2015-07-05T00:00:00+00:00 ((2457209j,0s,0n),+0s,2299161j)>=>5}

You will have only three key-value pairs, not 5 as you expect, because hash in Ruby is collection of unique keys and their values.

Upvotes: 1

Related Questions