Reputation: 532
I have a hash object (class name 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}
}
And I has a params object( class name ActiveSupport::HashWithIndifferentAccess)
h2 = {
"hot_products"=>{"enabled"=>"1"},
"recent_products"=>{"enabled"=>"0"},
"event_promotion"=>{"enabled"=>"1"}
}
And I want to merge these object using deep_merge
h1.deep_merge(h2)
Then I got:
{
: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"}
}
Does anyone know how can I merge these two object?
Upvotes: 0
Views: 265
Reputation: 11
Try this,
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}}
Upvotes: 1
Reputation: 23661
Issue is h1
has symbol keys and h2
has string keys
Make h1
as 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
and
h2 = {
"hot_products"=>{"enabled"=>"1"},
"recent_products"=>{"enabled"=>"0"},
"event_promotion"=>{"enabled"=>"1"}
}
Now, you can deep_merge
the hash and it will return you proper result
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}
}
Upvotes: 2