How to use the new class method In Ruby
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"]
How to initialize array in Ruby
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.