In this post, we will learn about arrays and the operations we can perform on them.

Array is the most common data structures we use in our programs. They are used to store data that can be accessed using index. In Ruby, an array may contain different type of data unlike in Java and C# where array stores similar type of data.

The starting value of array index in Ruby is 0 whereas the ending value is size of array – 1.

To declare an array, we use:

Syntax

array_name = Array.new([ .. ])

or

array_name = []

A blank array with 5 elements can be declared as:

array_name = Array.new(5)

All of the 5 values would be null in this case. If you want to initialize all values with some default value, use:

array_name = Array.new( 5, 0 )

All the array values will be 0 now.

Let us see some examples:

Calculating sum of even numbers

numbers = [1,2,3,4,5,6]

sum = 0
numbers.each do |x|
  if x%2 ==0 then
    sum += x
  end
end

puts sum

Same program using for loop

numbers = [1,2,3,4,5,6]

sum = 0
for i in 0..numbers.size-1
  if numbers[i]%2 == 0 then
    sum += numbers[i]
  end
end

puts sum

Adding items to array

We can add items to an existing array using any of the following methods:

numbers = [1,2,3,4]

numbers << 5            # adds item to the end of array

numbers.push(5)         # adds item to the end of array

numbers.unshift(5)      # adds item to the start of array

Removing elements from array

To remove an item from array, we can use:

numbers = [10,20,30,40]

numbers.pop               # removes 40

numbers.shift             # removes 10

numbers.delete_at(2)      # removes the value 30

Combining array

We can easily combine two arrays by using the + operator. Here is an example:

numbers1 = [1,2,3]
numbers2 = [4,5,6]
numbers = numbers1 + numbers2
puts numbers

We can also write:

numbers = numbers1 + numbers2

as

numbers = numbers1.concat(numbers2)

We can also subtract one array from another.

numbers1 = [1,2,3,4]
numbers2 = [2,3,8]

numbers = numbers1 - numbers2

Output:

[1,4]

Reversing and rotating array

We can easily rotate or reverse an array. Here are some examples:

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

numbers.reverse!           #  [5,4,3,2,1]        ! means modify original array instead of returning

number.rotate!             #  [2,3,4,5,1]

number.rotate!(-1)         #  [5,1,2,3,4]

Removing duplicate values

We can remove duplicate values from array by calling the method uniq. Here is an example:

numbers = [1,2,3,1,5,2]

numbers.uniq!