×

ruby · level 2 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.