DEV Community

Kiran Mahale
Kiran Mahale

Posted on

Working Of Array in Ruby

Today, we are going to see how ruby adds elements into an array without specifying the size. Let’s start.
When we define an array in C then we create it for a particular size, right?
int array[ 10 ];
Here, we have defined an integer array array of size 10. So it will contain a maximum of 10 numbers. If we try to insert/push more than 10 elements then it will give an error. To add more element you need to increase the size of the array array.
But, in Ruby, we never define the size of the array, so how it is handling?

Following is the strategy that Ruby uses while creating an array and adding elements to it.
Whenever we define an array in ruby then it defines its size as 3 by default.
array = []
means in C
int array[3] = [];
So what will happen when we push more than 3 elements in array? It will create a new array of size 20 and copy all the elements from the old array to a new array and then it will insert a new element to it. So, ruby calculates the size of the new array when it is full, like 3, 20, 37, 56, 85 …..
You can check the following link which describes how they are calculating the size of the array when it is full and when we push a new element to it.
https://github.com/ruby/ruby/blob/ruby_2_0_0/array.c#L183

Top comments (0)