0
0
Rubyprogramming~5 mins

Dig method for nested access in Ruby

Choose your learning style9 modes available
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.
When you want to get a value inside a nested hash without errors if keys are missing.
When you have nested arrays and want to access elements safely.
When you want to avoid writing many if or nil checks for nested data.
When working with JSON-like data structures in Ruby.
When you want to simplify code that reads deeply nested data.
Syntax
Ruby
object.dig(key1, key2, ..., keyN)
You can pass multiple keys or indexes to dig to go deeper step by step.
If any key or index is missing, dig returns nil instead of raising an error.
Examples
Get the first name from a nested hash safely.
Ruby
person = { name: { first: "John", last: "Doe" } }
first_name = person.dig(:name, :first)
Access nested array elements using dig.
Ruby
data = [ [1, 2], [3, 4] ]
value = data.dig(1, 0)
Returns nil safely when trying to dig into a nil value.
Ruby
info = { user: { details: nil } }
result = info.dig(:user, :details, :age)
Sample Program
This program shows how to use dig to get nested values safely from a hash and array. It prints the first name, phone number, and safely returns nil for a missing city.
Ruby
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).inspect
OutputSuccess
Important Notes
dig returns nil if any key or index is missing, so you don't get errors.
You can use dig with hashes, arrays, or a mix of both.
If you expect a value might be missing, dig helps avoid extra checks.
Summary
dig lets you access nested data safely and simply.
It returns nil if any part of the path is missing.
Works with hashes and arrays for flexible nested access.