Ruby’s Hash#dig (added in Ruby 2.3) is kinda cool to dig into nested hashes and not worry about nested element not being there.

In the dark ages, we’d have to check manually if a nested element exists and digging into something like params[:user][:address][:street_number] would require a few checks to get to street_number.

Meet Hash#dig! We can simply do params.dig(:user, :address, :street_number) and if one of the elements is missing we’d just get nil.

Recently I learned one more trick. You can also dig based on the element position in the array. Example:

hash = { user: { addresses: [ { street_number: '123' }, { street_number: '29' } ] } }
hash.dig(:user, :addresses, -1, :street_number)
=> "29"

Note the third argument -1 in the example above. It means to select the last element of the array.