Close
Close

Arrays in Ruby


In English dictionary, array means collection. In Ruby also, it is a collection. But before starting to learn about arrays, first you should know their use. It is very useful to store data when they are large in number. Imagine that you have to make a software for a firm and they have to store the price of 100 different products. Definitely, you need something better than using 100 different variables. And here you can use an array. So, let's see this example of declaring an array:

a = [1,2,3,4,5]
puts a
Output
1
2
3
4
5

'a' is an array here. [ ] represents an array. In next the example, 'b' is an empty array

b = []
puts b
Output

Every element in an array has an index. We can access a particular element using the index of that element. The index of an array starts from 0. It means that the index of the first element will be 0, the second element will be 1 and so on. We access the particular element of an array using its index as given below:

array_name[index]

'array_name' is the name of the array and 'index' is the index of the element which we are trying to access.

element 2 3 15 8 48 13
index 0 1 2 3 4 5
array in ruby

This will be clear by an example.

b = [1,2,3,4]
puts b[0]
puts b[1]
Output
1
2

As we have seen here, b[0] gave us the first element i.e. 1. It means that index of the first element is 0. Similarly, b[1] gave us 2 and it is the second element.

We can also change the values of an array using their indices. Example of this is given below.

b = [1,2,3,4]
puts b[0]
b[0] = 5
puts b[0]
Output
1
5

b[0] = 5 : Here, b[0] will simply give you the access of the 1st element of the array and b[0] = 5 will make it 5.

It is not necessary for an array to contain only the same type of elements. We can also have:

a = [1,2.3,"string"]
puts a
Output
1
2.3
string

So in the above example, the array contains fixnum, float and string also.

Range


.. and ... ( double dot and triple dot ) are range operators in Ruby. These operators generate a sequence of numbers or characters given to them. (..) is the inclusive and (...) is the exclusive range operator. This means that (1..5) will generate from 1 to 5 but (1...5) will generate from 1 to 4. We use to_a to convert them into an array. An example is given below.

a = (1..5).to_a
b = (1...5).to_a
c = ('a'..'e').to_a
puts "#{a}"
puts "#{b}"
puts "#{c}"
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
["a", "b", "c", "d", "e"]

You can see that (1..5) includes 5 but (1...5) doesn't. See one more example on this.

a = (1..5)
puts "#{a.max}"
puts "#{a.min}"
Output
5
1

max and min are used to find the maximum and minimum values. The maximum value in (1..5) is 5 ( as it includes 5 also ) and the minimum value is 1.

One more important operator is ===. It is used to check whether a number lies in the range or not. It returns true if the number is in the range else false.

a = (1..5)
puts "#{a === 2}"
puts "#{a === 10}"
Output
true
false
As we know that 'a = 2' means that a is 2 and '2 = a' is not the same. In the same way, ( (1..5) === 2 ) will check whether 2 lies in (1..5) or not and not ( 2 === (1..5) )

Length of an array


One more important method of array is length or size. Both length and size are same and they give us the number of elements in an array. See an example on this to understand:

a = [1,2]
b = ["12",12,12.12]
c = (1..100).to_a
puts "#{a.size}"
puts "#{b.size}"
puts "#{c.size}"
puts "#{a.length}"
Output
2
3
100
2

Using while with array


We can use while loop to iterate over all the elements of an array. Let's do this for finding the sum of all the elements of an array.

a = [3,23,4,3,12,54,65,23,23,45,32,54,23]
sum = 0
i = 0
while (i<a.size)
  sum = sum+a[i]
  i=i+1
end
puts "#{sum}"
Output
364

a.size will give 13. So, 'i' will go up to 12.
sum = sum+a[i] -> initially, 'sum' is 0. Now going step by step:
i is 0, sum is 0 and a[0] is 3. So, sum = sum + a[i] will be sum = 0+3 i.e. 3. So, sum is 3 now.
Now i is 1, sum is 3 and a[1] = 23. So, sum = 3+23 will make sum 25.
And so on. This will go up to i = 12.

You can also take the numbers as input from the user using
a[i] = gets.chomp.to_i.
Try this, take 10 integers of an array from the user and calculate its sum.

We have a better way to iterate over the whole array using for loop. This you will study later.

Slicing an array


Slicing means cutting. We can cut an array as per our need using a method called slice. Let's look at an example on this:

slice in ruby
a = [3,23,4,3,12,54,65,23,23,45,32,54,23]
puts "#{a.slice(2)}"
puts "#{a.slice(2,4)}"
puts "#{a[2,4]}"
puts "#{a.slice(1..4)}"
puts "#{a[1..4]}"
Output
4
[4, 3, 12, 54]
[4, 3, 12, 54]
[23, 4, 3, 12]
[23, 4, 3, 12]

a.slice(index) or a[index] gives an element at index.
a.slice(start,length) or a[start,length] gives a subarray from index start upto the number of elements in length. 'a[2,4]' gave us subarray starting from index 2 i.e. 4 and upto 4 elements, so we got [4, 3, 12, 54]
a.slice(range) or a[range] gives a subarray with index in the range. So, we got a subarray with elements from index 1 to 4 i.e. [23, 4, 3, 12] when we used a[1..4].

Array inside another array


Yes, we can also have arrays inside other.

a = [[3,23,4], [4,2,2], [12,34,12]]
puts "#{a}"
puts a[1][1]
puts a[0][1]
puts a[2][1]
puts a[1][2]
Output
[[3, 23, 4], [4, 2, 2], [12, 34, 12]]
2
23
34
2

a[0][1] - a[0] is [3,23,4] and in this array, the element with index 1 is 23. So, a[0][1] is 23.

Useful methods


There are many useful methods which you can use when you need them.

push and pop

a = [1,2,3,4,5,6]
puts "#{a.push(2)}"
puts "#{a.pop}"
puts "#{a}"
Output
[1, 2, 3, 4, 5, 6, 2]
2
[1, 2, 3, 4, 5, 6]

push inserts an element in the end of an array.
pop removes and returns the last element.

reverse

a = [1,2,3,4,5,6]
puts "#{a.reverse}"
Output
[6, 5, 4, 3, 2, 1]

reverse reverses an array.

Using + with two arrays

a = [1,2,3]
b = [4,5,6]
puts "#{a+b}"
Output
[1, 2, 3, 4, 5, 6]

'+' joins two arrays

Using - with two arrays

a = [1,2,3,4,5,6]
b = [4,5,6]
puts "#{a-b}"
Output
[1, 2, 3]

Returns a new array with common elements in the two arrays deleted from the 1st array.

Using | with two arrays

a = [1,2,3,4,5,6]
b = [4,5,6,7,8,9]
puts "#{a|b}"
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

'|' joins two arrays but after deleting the dublicate elements from the 1st array.

clear

a = [1,2,3,4,5,6]
puts "#{a.clear}"
Output
[]

Removes all the elements from an array.

delete and delete_at

a = [1,2,3,4,5,6]
puts "#{a.delete(1)}"
puts "#{a}"
puts "#{a.delete_at(1)}"
Output
1
[2, 3, 4, 5, 6]
3

delete deletes the element after searching it in an array.
delete_at deletes an element at the index given to 'delete_at'.
So, 'a.delete(1)' deleted 1 from a and 'a.delete_at(1)' deleted the element at index 1.

empty?

a = [1,2,3,4,5,6]
b = []
puts "#{a.empty?}"
puts "#{b.empty?}"
Output
false
true

empty? checks if an array is empty or not. It returns true if the array contains no element, else it returns false.

sort

a = [12,23,12,4,31,23,34,13,34,21,21,32,43,5456,23,2323,23]
puts "#{a.sort}"
Output
[4, 12, 12, 13, 21, 21, 23, 23, 23, 23, 31, 32, 34, 34, 43, 2323, 5456]

sort arranges an array in ascending order.

Don't spend so much time trying to choose the perfect opportunity that you miss the right opportunity.
-Michael Dell


Ask Yours
Post Yours
Doubt? Ask question