๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Arrays

An array is an ordered list of values in one variable. Square brackets hold the items, and each item sits at a numbered place called an index.

An array in square brackets

Square brackets hold three names in order. p prints the array as one value.

names = ["Ana", "Bo", "Cy"]
p names

Reading items by index

Index 0 reads the first name. Index 2 reads the third name.

names = ["Ana", "Bo", "Cy"]
puts names[0]
puts names[2]

The last item with index -1

Index -1 counts from the end of the array. It reads the last name.

names = ["Ana", "Bo", "Cy"]
puts names[-1]

Changing one item

Index 1 gets a new name. p shows the array with the change in place.

names = ["Ana", "Bo", "Cy"]
names[1] = "Bea"
p names

Length and the empty array

length counts the items in the first array. An empty array holds no items, so its length is 0.

names = ["Ana", "Bo", "Cy"]
puts names.length
empty = []
puts empty.length
p empty

Example

scores = [70, 85, 90]
puts scores[0]
puts scores[-1]
scores[1] = 88
p scores
puts scores.length

Key points

  • Square brackets hold the items of an array.
  • The first item sits at index 0.
  • Square brackets with an index read the item at that index.
  • Index -1 reads the last item.
  • Square brackets with an index and a new value change that one item.
  • length counts how many items an array holds.

In this example, the scores array holds three numbers. The first puts prints the number at index 0, and the second prints the last number with index -1. Index 1 then gets the new value 88, and p shows the full array before the last line prints its length.

Note

Reading an index past the end of an array gives nil, not an error.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

The array is names = ["Ana", "Bo", "Cy"]. What does puts names[1] print?