无法将Hash对象与ActiveSupport :: HashWithIndifferentAccess合并

时间:2017-03-23 06:41:12

标签: ruby-on-rails ruby hash

我有一个哈希对象(类名Hash):

h1 = {
 :hot_products=>{:enabled=>true, :always_enable=>false, :order=>0},
 :recent_products=>{:enabled=>true, :always_enable=>true, :order=>1},
 :event_promotion=>{:enabled=>true, :always_enable=>false, :order=>2}
}

我有一个params对象(类名ActiveSupport :: HashWithIndifferentAccess)

h2 = { 
 "hot_products"=>{"enabled"=>"1"},
 "recent_products"=>{"enabled"=>"0"},
 "event_promotion"=>{"enabled"=>"1"}
}

我想使用deep_merge

合并这些对象

h1.deep_merge(h2)

然后我得到了:

{
 :hot_products=>{:enabled=>true, :always_enable=>false, :order=>0},
 :recent_products=>{:enabled=>true, :always_enable=>true, :order=>1},
 :event_promotion=>{:enabled=>true, :always_enable=>false, :order=>2},
 "hot_products"=>{"enabled"=>"1"},
 "recent_products"=>{"enabled"=>"0"},
 "event_promotion"=>{"enabled"=>"1"}
}

有谁知道如何合并这两个对象?

2 个答案:

答案 0 :(得分:2)

问题是h1有符号键,h2有字符串键

h1设为HashWithIndifferentAccess

h1 = {
 :hot_products=>{:enabled=>true, :always_enable=>false, :order=>0},
 :recent_products=>{:enabled=>true, :always_enable=>true, :order=>1},
 :event_promotion=>{:enabled=>true, :always_enable=>false, :order=>2}
}.with_indifferent_access

h2 = { 
 "hot_products"=>{"enabled"=>"1"},
 "recent_products"=>{"enabled"=>"0"},
 "event_promotion"=>{"enabled"=>"1"}
}

现在,您可以deep_merge哈希,它会返回正确的结果

h1.deep_merge(h2)

{
 "hot_products"=>{"enabled"=>"1", "always_enable"=>false, "order"=>0},
 "recent_products"=>{"enabled"=>"0", "always_enable"=>true, "order"=>1}, 
 "event_promotion"=>{"enabled"=>"1", "always_enable"=>false, "order"=>2}
}

答案 1 :(得分:1)

试试这个,

h1=ActiveSupport::HashWithIndifferentAccess.new(h1)
h1.deep_merge(h2)
=> {"hot_products"=>{"enabled"=>"1", "always_enable"=>false, "order"=>0}, "recent_products"=>{"enabled"=>"0", "always_enable"=>true, "order"=>1}, "event_promotion"=>{"enabled"=>"1", "always_enable"=>false, "order"=>2}}