The “dig” method
Learn what the dig method is and how to use it in Ruby.
We'll cover the following...
Iteration over nested data structure
Let’s look at the following nested data structure:
users = [
{ first: 'John', last: 'Smith', address: { city: 'San Francisco', country: 'US' } },
{ first: 'Pat', last: 'Roberts', address: { country: 'US' } },
{ first: 'Sam', last: 'Schwartzman' }
]
The structure above has its data scheme. The format is the same for every record, and there are three total records in this array, but the two last records are missing something. For example, the second one is missing the city
. The third record doesn’t have an address
. What we want is to print all the cities from all the records, and in the future we might have more than three.
The first thing that comes to our mind is iteration over the array of elements and using standard hash access:
users.each do |user|
puts user[:address][:city]
end
Let’s give it a ...