Introduction
The dig method helps you get values deep inside nested hashes or arrays without writing many checks. It makes your code cleaner and safer.
object.dig(key1, key2, ..., keyN)
person = { name: { first: "John", last: "Doe" } }
first_name = person.dig(:name, :first)data = [ [1, 2], [3, 4] ] value = data.dig(1, 0)
info = { user: { details: nil } }
result = info.dig(:user, :details, :age)profile = {
user: {
name: {
first: "Alice",
last: "Smith"
},
contacts: [
{ type: "email", value: "alice@example.com" },
{ type: "phone", value: "123-456-7890" }
]
}
}
# Get first name
puts profile.dig(:user, :name, :first)
# Get phone number
puts profile.dig(:user, :contacts, 1, :value)
# Try to get a missing key safely
puts profile.dig(:user, :address, :city).inspectdig method do when used on a nested hash or array?digdig method is designed to access nested data structures like hashes or arrays without raising errors if a key or index is missing.dig returns nil instead of raising an error.dig on a hash h = {a: {b: 2}} to get the value 2?dig method is called with arguments representing the nested keys or indexes, separated by commas inside parentheses.h.dig(:a, :b), which is the correct syntax. h.dig[:a][:b] uses square brackets incorrectly. h[:a].dig(b) uses b without the leading colon :, causing NameError. h.dig(:a).dig(b) chains dig calls unnecessarily and uses b without :, causing NameError.data = {user: {profile: {name: "Alice", age: 30}}}
puts data.dig(:user, :profile, :name)dig method looks for the key :user in data, then :profile inside that, then :name inside profile.dig returns the string "Alice".info = {a: {b: 1}}
puts info.dig(:a, :c)dig returns nil safely when a key is missing.settings = {theme: {colors: [{name: "red", code: "#f00"}, {name: "green", code: "#0f0"}]}}dig call correctly retrieves the color code for the second color?colors is an array of hashes. The second color is at index 1 (arrays start at 0).dig(:theme, :colors, 1, :code). settings.dig(:theme, :colors, 1, :code) matches this.Pass the test and this pattern moves unknown