Initializing Arrays in Ruby
A new array can be created by using two different ways in ruby and can contain different types of objects.
Using literal constructor.
And, by explicitly calling ::new
Array.new
provides us with some control to pass options(arguments).
Array.new(size, default)
: size
the initial size of the Array and default
a default object.
The default
argument populates the array with a default value. It is recommended to use only symbols
, numbers
or boolean
to instantiate arrays i.e immutable objects.
Now, if you try to pass Hash.new
as the default
argument and then assign the value to any of the hash element, the same object will be used as the value for all the array elements.
If we check the object_id
, the object ids are same for all the elements.
To create a array with seperate objects you can pass a block.
Now, if we check the object ids agian, they are different for each element.
Using this method you can pass mutable objects such as hashes
, strings
or arrays
.