Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Data Types  ›  Lesson

Arrays and Hashes

Arrays 12 minArrays are ordered lists found by numeric position starting at zero, while hashes store key-value pairs found by key.

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")  # => true

An 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.

Storing Bean Cart dataStep 1 of 4
  1. Orders waiting

    You serve them in the order they arrived, so an Array: queue = ["latte", "tea"].

Drills

Answer fast — trust the rule.

quick drill

With queue = ["latte", "tea", "mocha"], what is queue[1]?

quick drill

What is queue[-1] for the same array?

quick drill

Which structure best stores each drink's price for quick lookup by name?

quick drill

With menu = { tea: 2.50 }, what does menu.fetch(:chai) do?

quick drill

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 fetch when missing means a bug.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainQueue and menu

Explain why Bean Cart stores its waiting orders in an array but its prices in a hash, and show how to look up the price of the first order in the queue. Mention what happens with a missing key.