Ruby - Using Array.new method

Introduction

You can create arrays using the usual object construction method, new.

Optionally, you can pass an integer to new to create an empty array of a specific size with each element set to nil.

Or you can pass two arguments: the first to set the size of the array and the second to specify the element to place at each index of the array, like this:

Demo

a = Array.new                            # an empty array 
puts a#   ww w  .  j a  va2 s  .  c om

a = Array.new(2)                         # [nil,nil] 
puts a

a = Array.new(2,"hello world")           # ["hello world","hello world"] 
puts a

Result

Related Topic