Ruby merge Vs deep_merge

This post will help you understand the difference between Ruby's merge and Rails deep_merge method.


Ruby's merge method merges one hash into another, as it's name suggest

{ first_name: 'John' }.merge({ last_name: 'Doe' })
=> {:first_name=>"John", :last_name=>"Doe"}

Now lets say we have following 2 Hash objects

user1 = { name: 'John', address: { city: 'City' } }
user2 = { name: 'John', address: { zip: '12345' } }

And if we use .merge() this time the result will be:

=> {: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

=> {:name=>"John", :address=>{:city=>"City", :zip=>"12345"}}

NOTE: .deep_merge is a rails method and .merge is a ruby's method