Arrays and Hashes
Bean Cart has a queue of orders waiting to be made, and a menu where each drink has a price. The queue is about order: first come, first served. The menu is about lookup: what does a mocha cost? Ruby's two main collections match those two jobs exactly.
The rule
Arrays are found by position; hashes are found by key.
An Array is an ordered list inside square brackets. Positions, called indexes, start at 0, and negative indexes count from the end:
queue = ["latte", "tea", "mocha"]
queue[0] # => "latte"
queue[-1] # => "mocha"
queue[10] # => nil (no such position)
queue.size # => 3
queue << "chai" # add to the end
queue.shift # => "latte", removed from the front
queue.include?("tea") # => trueAn array can hold any mix of objects, even other arrays, but in practice you keep one kind of thing per array.
A Hash stores key-value pairs inside curly braces. You look up a value by its key, not by position:
menu = { latte: 4.50, mocha: 5.00, tea: 2.50 }
menu[:mocha] # => 5.0
menu[:chai] # => nil
menu[:chai] = 4.00 # add a new pair
menu.keys # => [:latte, :mocha, :tea, :chai]
menu.fetch(:cocoa) # raises KeyError: key not found
menu.fetch(:cocoa, 0) # => 0 (the default you supplied)The latte: 4.50 style is shorthand for the older :latte => 4.50. You still need the => form when the keys are not symbols, such as { "latte" => 4.50 }. Keys are unique: assigning to an existing key replaces its value. Hashes also remember the order in which keys were added.
Use fetch when a missing key would be a bug: it fails loudly instead of quietly handing you nil.
The shortcut
Ask "How will I find one item?" By its place in line ("the first order", "the last one"): Array. By a name ("the price of tea"): Hash.
Orders waiting
You serve them in the order they arrived, so an Array:
queue = ["latte", "tea"].
Drills
Answer fast — trust the rule.
With queue = ["latte", "tea", "mocha"], what is queue[1]?
What is queue[-1] for the same array?
Which structure best stores each drink's price for quick lookup by name?
With menu = { tea: 2.50 }, what does menu.fetch(:chai) do?
With menu = { tea: 2.50 }, what happens after menu[:tea] = 3.00?
Remember
- Arrays are found by position (from 0); hashes are found by key.
- Ask "how will I find one item?" Place in line: Array. Name: Hash.
- Trap: a missing index or key quietly returns nil; use
fetchwhen missing means a bug.
