Skip to the workspace
Pebellslearn by building
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.

ruby / Arrays and Hashes

Explore each scene at your own pace.

01 · The rule

The rule

Arrays and Hashes

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

Choose positional storage or keyed records and inspect missing values.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.