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.

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 –



filter_none

edit
close

play_arrow

link
brightness_4
code

# creating array using new method  
# without passing any parameter 
arr = Array.new() 
  
# displaying the size of arrays 
# using size method 
puts arr.size 

chevron_right


Output:

0

Passing size of array as parameter –

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 

chevron_right


Output:

7

Passing size of array and elements as parameter –

filter_none

edit
close

play_arrow

link
brightness_4
code

# creating array using new method  
# passing two parameters i.e. the  
# size of array & element of array 
arr3 = Array.new(4, "GFG"
  
puts "#{arr3}"

chevron_right


Output:

["GFG", "GFG", "GFG", "GFG"]

Using literal constructor[] –

In Ruby, [] is known as the literal constructor which can be used to create the arrays.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

arr1 = ('1'..'6').to_a  
# displaying array elements 
puts "#{arr1}"
  
arr2 = *'11'..'15'
puts "#{arr2}"

chevron_right


Output:

["1", "2", "3", "4", "5", "6"]
["11", "12", "13", "14", "15"]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.