Use hash dig method to get the nested hash values. Sometimes you have to navigate to multi-level hash to get values. For example, consider the below user hash.
Don’ts
users = [ { profile: { name: "saran", address: { city: "chennai" } } }, { profile: { name: "kumar" } } ] user = users.first user[:profile][:address][:city] => "chennai" user = users.last user[:profile][:address][:city] => NoMethodError: undefined method `[]' for nil:NilClass [/code] How we can avoid this error? Generally developers will add conditions like below,
user[:profile][:address][:city] if user[:profile] && user[:profile][:address]
Do’s
Ruby provides some special tricks to handle this situation.user = users.first user.dig(:profile, :address, :city) => "chennai" user = users.last user.dig(:profile, :address, :city) => nil
Leave a Reply