ruby · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Real data comes : hashes inside arrays inside hashes.
Apps ask other programs for data through an , and the reply is usually JSON. Real replies are nested: a hash can hold arrays, and those arrays can hold more hashes. Gwecode runs without the internet, so here a heredoc plays the part of the reply.
Reach inside one layer at a time: weather[:days][0][:temp]. Or down in one go with .dig(:days, 0, :temp), which takes the same steps but gives nil instead of crashing if anything along the way is missing.
require "json"
reply = <<~JSON
{"city": "Leeds", "days": [{"day": "Mon", "temp": 14}, {"day": "Tue", "temp": 11}]}
JSON
weather = JSON.parse(reply, symbolize_names: true)
puts weather[:city]
puts weather[:days][0][:temp]
p weather.dig(:days, 5, :temp)
p weather[:days].map { |day| day[:day] } Read a long lookup from left to right, one step deeper each time.
guess first
Dig for the answer. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
order = { id: 7, items: [{ name: "pizza", qty: 2 }, { name: "cola", qty: 3 }] }
puts order[:items][1][:name]
puts order[:items].sum { |item| item[:qty] }
p order.dig(:customer, :name)
your turn
Your turn. Read a pretend film API.
Pick a film number, 0, 1 or 2. Then fill in the key to show: title or year.
fix it
The weather app crashes on the forecast. Fix it!
- Read the error. Ruby tried to look inside
nil. Which lookup found nothing? JSON.parsegives string keys, soweather[:forecast]isnil. Ask for symbol keys instead.- Change line 5 to weather = JSON.parse(reply, symbolize_names: true), then press run.
nailed it
you can dig through any reply now. :D
- APIs send nested data, usually as JSON.
- Step in one layer at a time:
[:days][0][:temp]. .diggivesnilinstead of crashing on a missing step.
new words in your collection
- API
- nested
- dig
This lesson isn’t saved. A free account remembers every lesson you finish.