Use dig method to get value from deeply nested key
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.
Learn how to extracts the nested value specified by the sequence of key objects by calling dig at each step, returning nil if any intermediate step is nil.
Example data
Lets say we have following Hash to work on, this can be a rails params object or any other Hash object
params = { name: "John", address: { primary: { city: 'Pokhara' } } }
And we want to get the value of city from the given object, and one way to do is:
params[:address] && params[:address][:primary] && params[:address][:primary][:city]
=> "Pokhara"
we need to do that, because if lets say address or primary key is empty than we will get
undefined method `[]' for nil:NilClass (NoMethodError)
And ruby has a clean and easy way to extract such values by using .dig method
params.dig(:address, :primary, :city)
=> "Pokhara"
In this case, if address or primary key do not exists, or have nil as a value, than it will return nil as result without throwing error.

