Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 9 of 23 · Ruby 3.2

Store an ordered list

Create an array, read entries by position and update a list.

Learn

An Array stores an ordered list of values. Write its entries between square brackets, separated by commas. An index is a position: index 0 selects the first entry, index 1 the second, and so on.

Use array[index] to read an entry and array[index] = value to replace it. push(value) appends an entry, and length reports the number of entries. p displays an array with brackets so its structure is visible.

A negative index counts back from the end: -1 selects the last entry. Reading an index outside an array returns nil.

Example

supplies = ["paper", "pens", "tape"]
puts supplies[0]
supplies.push("labels")
p supplies
puts supplies.length

Experiment

  • The second stop has changed. Predict the list, then edit the assignment to replace the third stop instead.

  • Predict the last customer and queue length. Add another push before the two puts calls and check how both readings change.

  • Predict both readings. Change index 2 to index 1 and compare an absent entry with a present entry.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.