top of page

ūüöÄ Ruby Tip: Have you heard of the `dig` method?

Atualizado: 21 de mar.

It's an elegant way to access values in hashes and arrays safely and efficiently, and it's instrumental when you're unsure if the key or index exists.

# Example with hash
person = { name: { first: "John", last: "Doe" }, age: 30 }
puts person.dig(:name, :first) # Output: "John"

# Example with array
data = [[1, 2], [3, 4], [5, 6]]
puts data.dig(1, 0) # Output: 3

# If a key or index doesn't exist, the method returns nil
puts person.dig(:address, :city) # Output: nil

data = [
  { person: { name: "John", age: 30 } },
  { person: { name: "Jane", age: 25 } }
]
puts data.dig(0, :person, :name)  # Output: "John"

Use dig to prevent errors when accessing deeply nested data structures in Ruby! ūüĒć‚ú®

◊™◊í◊ē◊Ď◊ē◊™


Captura de tela de 2024-01-01 22-06-25.png

Hi, I'm Rodrigo Toledo

A full-stack developer skilled in both front-end and back-end development, building and maintaining web applications

  • Facebook
  • Youtube
  • LinkedIn
  • Instagram

I don't know everything, help me

Every day, I try to improve what I know about frameworks, and when this occurs, I'll try to share it with the community. Every day, I try to improve my knowledge about frameworks. When this happens, I will try to share it with the community.

Subscribe

Thanks for submitting!

bottom of page