This post will help you understand the difference between Ruby’s merge and Rails deep_merge method.
Merge
Ruby’s merge method merges one hash into another, as it’s name suggest
1
2
{ first_name: 'John' }.merge({ last_name: 'Doe' })
=> {:first_name=>"John", :last_name=>"Doe"}
Now lets say we have following 2 Hash objects
1
2
user1 = { name: 'John', address: { city: 'City' } }
user2 = { name: 'John', address: { zip: '12345' } }
And if we use .merge() this time the result will be:
1
2
user1.merge(user2)
=> {:name=>"John", :address=>{:zip=>"12345"}}
Deep Merge
And if we want to merge both city and zip addresses for the user, then we need to use .deep_merge() method
1
2
user1.deep_merge(user2)
=> {:name=>"John", :address=>{:city=>"City", :zip=>"12345"}}
NOTE:
.deep_mergeis a rails method and.mergeis a ruby’s method