我有一个哈希对象(类名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"}
}
有谁知道如何合并这两个对象?
答案 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}}