How to Use Arrays in Ruby

09/19/2021

Contents

In this article, you will learn how to use arrays in Ruby.

How to use arrays

In Ruby, arrays are ordered collections of objects, which can be accessed and manipulated in various ways. Here are some basic examples of how to use arrays in Ruby:

Creating an Array

To create an array in Ruby, you can use square brackets [] with a list of values separated by commas. For example:

my_array = [1, 2, 3, 4, 5]

You can also create an empty array by using Array.new or []. For example:

empty_array = Array.new
another_empty_array = []

Accessing Elements

You can access elements in an array using their index number. In Ruby, arrays are zero-indexed, meaning that the first element has an index of 0. For example:

my_array = [1, 2, 3, 4, 5]
puts my_array[0] # Output: 1
puts my_array[2] # Output: 3

You can also access elements from the end of the array using negative index numbers. For example:

my_array = [1, 2, 3, 4, 5]
puts my_array[-1] # Output: 5
puts my_array[-3] # Output: 3

Adding and Removing Elements

You can add elements to an array using the << operator or the push method. For example:

my_array = [1, 2, 3]
my_array << 4
my_array.push(5)
puts my_array # Output: [1, 2, 3, 4, 5]

You can remove elements from an array using the pop method or the delete_at method. For example:

my_array = [1, 2, 3, 4, 5]
my_array.pop
my_array.delete_at(2)
puts my_array # Output: [1, 2, 4]

Iterating through an Array

You can iterate through an array using the each method. For example:

my_array = [1, 2, 3, 4, 5]
my_array.each do |number|
  puts number
end

This will output each element of the array on a new line.