🚀 Ruby Tip: Have you heard of the `dig` method?
Atualizado: 21 de mar. de 2024
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! 🔍✨
Yorumlar