ruby arrays can hold multiple values. The minimum elements of an array is zero, but they usually have two or more. Each element in an array has a unique index.

The index starts at zero (0). That means to access the first element of an array, you need to use the zeroth index.

Download Free Ruby Ebook

Arrays in ruby

Example

The program below is an example of an array loop in ruby.
The array we define has several elements. We print the first item with the zeroth index.

1
2
3
4
5
#!/usr/bin/ruby

a = Array[1, 2, 3, 4,5]
puts "First element: #{a[0]}"
puts "Second element: #{a[1]}"

Upon running this program it will output the first (1) and second (2) element of the array. They are referenced by the zeroth and first index. In short: computers start counting from 0.

1
ruby example6.rb

This program will output:

1
2
First element: 1
Second element: 2

The index should not be larger than the array, that could throw an error or unexpected results.

Exercises

  1. Create an array with the number 0 to 10
  2. Create an array of strings with names