Ruby Arrays Tutorial

In this section, we will learn what the Arrays are and how to use them in Ruby.

What is Array in Ruby?

The Ruby Array is a collection type object! We say it’s a collection type object because it is capable of holding multiple values of different types at the same time!

For example, you can create an object with 10 values each of different types and store all of them in one object of type array!

Now using the array object, we can easily access the values it stored in order to retrieve and modify if necessary.

How to Declare Arrays in Ruby?

There are two different methods of creating an array in Ruby.

The first one is called Array Literal. We use Array literals when we know in advance the elements we want to add to the target array.

Here’s the syntax of the Array Literal:

variable_name = [element1, element2, element_n]

`variable_name`: this is the variable that holds a reference to the created array.

`[]`: in order to create an array literal we set a pair of brackets like `[]` and inside this pair we set the elements we want the array to have. So the `element1`, `element2` and element_n in this example are the values the array has.

Note that the data type of the elements we set for an array could be different! For example, the first element can be of type string, then the second one of type integer and so on…

The second form of creating an array is by using the Array class! This form is mainly used when we don’t know what elements will be set in the target array! So we call the Array class in order to create a new array object and then assign the elements in later time.

Here’s the syntax of using the Array class:

Array.new

Array.new(length)

Array.new(length, value)

The first form of using the Array class creates an empty array for you. The size of the array is also undefined in this form.

The second form of using the Array class creates an array of the specified length! For example, if the value is set to 20, that means the array should be big enough to take 20 elements.

Note: the size of an array in Ruby increases automatically! This means if you create an empty array, it will automatically increase its size whenever you add a new element to the list.

The last form of creating an array using the Array class takes two arguments: the first argument defines the length of the array and the second value sets the default value for that array! By default, the default value is set to the value “nil”. But now we have this ability to change the default value into something other than nil.

Example: creating an array in Ruby

arr1 = [1, "Jack",true, "Ellen"]

arr2 = Array.new

arr3 = Array.new(5)

arr4 = Array.new(5,"One")

puts arr1, arr2, arr3, arr4

puts arr1.length, arr2.length, arr3.length, arr4.length

Output:

1

Jack

true

Ellen

One

One

One

One

One

4

0

5

5

Access and Change the Elements of an Array in Ruby

You should know that elements in an array have indexes!

The first element of an array has the index number 0, the second one has the index of 1 and so on.

Now using this index number, we can access the target value in the array.

Here’s the syntax on how to access an element in an array:

array_name[index-number]

`array_name`: this is the name of the array we want to access.

`[index-number]`: now in the pair of brackets we set the index of the element we want to access.

Note that if we use this syntax on the left side of the assignment operator, that means the purpose is to change the current element in that index.

For example:

array_name[10] = 15

This means we want to access the index number 10 of the `array_name` and replace its value with the value 15.

Now besides the left side of the assignment operator, in any other places we try and access an element of an array, we will get the current value in the specified index.

For example:

method_name (array_name[10])

This means we want to pass the current value in the index number 10 of the `array_name` as the argument of the method_name.

Example: accessing and changing Ruby Array Elements

arr1 = [1, "Jack",true, "Ellen"]

puts arr1

puts "***"

arr1 [2] = "John"

puts arr1

puts "***"

second_element = arr1[1]

puts second_element

Output:

1

Jack

true

Ellen

***

1

Jack

John

Ellen

***

Jack

Array Length in Ruby

The length of an array is the number of elements currently it has.

For example, if an array has 20 elements, then the length of that array will be 20.

We use the `length` method to get the current length of an array.

Example: getting the length of an array in Ruby

arr1 = [1, "Jack",true, "Ellen"]

arr2 = Array.new

arr3 = Array.new(5)

arr4 = Array.new(5,"One")

puts arr1.length, arr2.length, arr3.length, arr4.length

Output:

4

0

5

5

Ruby Array: Out of Range Indexes

When working with Arrays, you can call an index number that is outside of the range of elements that the array currently has.

For example, if the array has like 10 elements, you can call the indexes from 0 to 9 and get an actual value from the list.

But there’s no error if you try to call an element in an index number like 100 or 40, etc.

Now, if you call an index that is outside the range of an array, two things can happen:

  • if you call the index in order to put a value in that index (which means we’ve called the index on the left side of the assignment operator), then the length of the array will grow to handle the new element and index as well.
  • But if you call the index in order to get the value without assigning any new value there, then only the value `nil` will return. So the length of the array will stay the same.

Example: setting and accessing values that are beyond the range of an array in Ruby

arr1 = [1, "Jack",true, "Ellen"]

arr2 = Array.new(5,"One")

puts "The length of the arr1 array is: #{arr1.length}"

puts "The length of the arr2 array is: #{arr2.length}"

result = arr2[400]

arr1[10] = "Peter"

if result

   puts "The value of the result is: #{result}"

else

   puts "The value of the result is nil"

end

puts "***"

puts "The length of the arr2 is: #{arr2.length}"

puts "The length of the arr1 array is: #{arr1.length}"

Output:

The length of the arr1 array is: 4

The length of the arr2 array is: 5

The value of the result is nil

***

The length of the arr2 is: 5

The length of the arr1 array is: 11

As you can see, trying to access the value in an index number that doesn’t exist in an array won’t change its size and we get only the value nil.

But if we add a new element to an index of an array that is out of range of that array, it will cause the array to grow in length to cover the new index as well.

Looping an Array in Ruby

There are multiple ways to loop through the elements of an array! For example, we can use the Ruby for loop or the while loop to iterate the elements of an array!

Example: using for loop to iterate an Array in Ruby

arr1 = [1, "Jack",true, "Ellen"]

for element in arr1 do

    puts "The value is: #{element}"

end

puts "Now using while loop to iterate the same array: "

ind = 0

while ind < arr1.length

    puts "The value is: #{arr1[ind]}"

    ind +=1

end

Output:

The value is: 1

The value is: Jack

The value is: true

The value is: Ellen

Now using while loop to iterate the same array:

The value is: 1

The value is: Jack

The value is: true

The value is: Ellen

Ruby Array: Elements with different data types

As mentioned before, Array objects don’t care what type of value we set as their elements! This means the entire elements of an array could be of the same type or a combination of multiple different types.

Example: creating elements with different data types in Ruby array

arr1 = ["Ellen","Hattie","Jin","Omid","Elon","John"]

arr2 = [1,2,3,4,5,6,7,8,9,10]

arr3 = [true, false, 1,2,3,4, "Jack","John",true, 2.3, 4, false, nil]

Ruby Array: Removing elements from Arrays

There are two ways to remove an element from an array!

The first one is to call the `pop` method that will remove the last element of the array (it will also return the removed element as a result of calling the method).

The second one is to call the `shift` method, which will remove the first element of the array. (This one also returns the removed element as a result of calling it).

Example: removing elements from an array in Ruby

arr = [true, false, 1,2,3,4, "Jack","John",true, 2.3, 4, false, nil]

puts "The size of the array before calling the pop method: #{arr.length}"

remElement = arr.pop

puts "The size of the array after calling the pop method: #{arr.length}"

puts "The removed element: #{remElement}"

puts "The array before calling the shift method two times: "

puts arr.to_s

puts "The array after calling the shift method two times: "

arr.shift

arr.shift

puts arr.to_s

Output:

The size of the array before calling the pop method: 13

The size of the array after calling the pop method: 12

The removed element:

The array before calling the shift method two times:

[true, false, 1, 2, 3, 4, "Jack", "John", true, 2.3, 4, false]

The array after calling the shift method two times:

[1, 2, 3, 4, "Jack", "John", true, 2.3, 4, false]

More to Read:

Ruby References Tutorial

Ruby Multidimensional Arrays

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies