How to Create a Ruby Array

09/23/2021

Contents

In this article, you will learn how to create a Ruby array.

Creating a Ruby array

A Ruby array is an ordered collection of elements, each of which can be of any data type. You can create a Ruby array in several ways, including:

Using the literal notation

You can create an array using square brackets, separating the elements with commas. For example:

my_array = [1, 2, "three", true]

This creates an array with four elements: the integer 1, the integer 2, the string “three”, and the boolean value true.

Using the Array.new constructor

You can also create an array using the Array.new constructor, which takes one or two arguments. The first argument specifies the size of the array, and the second argument is an optional initial value for all elements of the array. For example:

my_array = Array.new(3, "hello")

This creates an array with three elements, all of which are the string “hello”.

Using a range

You can create an array using a range, which is specified by two dots (..) or three dots (…). The range specifies the first and last element of the array. For example:

my_array = (1..5).to_a

This creates an array with five elements: the integers 1, 2, 3, 4, and 5.

Using a block

You can also create an array using a block, which is enclosed in curly braces {}. The block specifies the logic for generating each element of the array. For example:

my_array = (1..5).map { |x| x * 2 }

This creates an array with five elements: the integers 2, 4, 6, 8, and 10. The block specifies that each element should be twice the value of the corresponding integer in the range.

Using the %w notation

You can create an array of strings using the %w notation, which allows you to specify a list of space-separated strings without quotes. For example:

my_array = %w(apple banana orange)

This creates an array with three elements: the strings “apple”, “banana”, and “orange”.

Using the %i notation

You can create an array of symbols using the %i notation, which allows you to specify a list of space-separated symbols without colons. For example:

my_array = %i(one two three)

This creates an array with three elements: the symbols :one, :two, and :three.