Ruby merge Vs deep_merge
I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.
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
{ 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:
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
user1.deep_merge(user2)
=> {:name=>"John", :address=>{:city=>"City", :zip=>"12345"}}
NOTE:
.deep_mergeis a rails method and.mergeis a ruby's method

