How to initialize array in Ruby
Last Updated :
24 Oct, 2019
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 –
arr = Array . new ()
puts arr.size
|
Output:
0
Passing size of array as parameter –
arr2 = Array . new ( 7 )
puts arr2.length
|
Output:
7
Passing size of array and elements as parameter –
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.
arr = Array [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ]
puts "#{arr}"
puts "Size of arr is: #{arr.size}"
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
puts "#{arr1}"
arr2 = * '11' .. '15'
puts "#{arr2}"
|
Output:
["1", "2", "3", "4", "5", "6"]
["11", "12", "13", "14", "15"]
Share your thoughts in the comments
Please Login to comment...