How to initialize array in Ruby
Last Updated :
24 Oct, 2019
Improve
In this article, we will learn how to initialize the array in Ruby. There are several ways to create an array. Let’s see each of them one by one.
Using the new class method:
new method can be used to create the arrays with the help of dot operator. Using arguments we can provide the size to array and elements to array.
Without any argument –
# creating array using new method # without passing any parameter arr = Array . new () # displaying the size of arrays # using size method puts arr.size |
Output:
0
Passing size of array as parameter –
# creating array using new method # passing one parameter i.e. the # size of array arr2 = Array . new ( 7 ) # displaying the length of arrays # using length method puts arr2.length |
Output:
7
Passing size of array and elements as parameter –
# creating array using new method # passing two parameters i.e. the # size of array & element of array arr3 = Array . new ( 4 , "GFG" ) puts "#{arr3}" |
Output:
["GFG", "GFG", "GFG", "GFG"]
Using literal constructor[] –
In Ruby, [] is known as the literal constructor which can be used to create the arrays.
# Ruby program to demonstrate the # creation of array using literal # constructor[] and to find the size # and length of array # creating array of characters arr = Array [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ] # displaying array elements puts "#{arr}" # displaying array size puts "Size of arr is: #{arr.size}" # displaying array length puts "Length of arr is: #{arr.length}" |
Output:
["a", "b", "c", "d", "e", "f"] [1, 2, 3, 4, 5, 6, 7] Size of arr is: 6 Length of arr is: 6
Using range –
arr1 = ( '1' .. '6' ).to_a # displaying array elements puts "#{arr1}" arr2 = * '11' .. '15' puts "#{arr2}" |
Output:
["1", "2", "3", "4", "5", "6"] ["11", "12", "13", "14", "15"]