如何在Ruby中合并两个相同的对象

时间:2017-12-05 00:46:38

标签: ruby

我有两个看起来像这样的对象:

obj1 = { hostname: "test",
         cpu: 20, 
         disk_space: nil,
         ram: nil,
         check_time: "2017-12-05 01:28" }

obj2 = { hostname: "test",
         cpu: nil,
         disk_space: 3000,
         ram: nil, 
         check_time: "2017-12-05 01:28"}

我想从disk_space: nildisk_space: 3000覆盖obj2。我想基本覆盖nils

new_obj = { hostname: "test",
            cpu: 20,
            disk_space: 3000,
            ram: nil,
            check_time: "2017-12-05 01:28" }

我如何在Ruby中实现这一目标?

2 个答案:

答案 0 :(得分:2)

使用merge

obj1.merge(obj2) { |key, oldval, newval| oldval.nil? ? newval : oldval }
=> {:hostname=>"test", :cpu=>20, :disk_space=>3000, :ram=>nil, :check_time=>"2017-12-05 01:28"}

简而言之:

obj1.merge(obj2) { |_, v, w| v.nil? ? w : v }

答案 1 :(得分:2)

我更喜欢@StefanPochman的答案,但自从采取了这种方法以来,这是另一种方法。

obj1.merge obj2.select { |k,_| obj1[k].nil? }
  #=> {:hostname=>"test", :cpu=>20, :disk_space=>3000, :ram=>nil,
  #    :check_time=>"2017-12-05 01:28"}