Skip to content
class method

Array.new

[unchecked out Elem] () -> ::Array[Elem]
[unchecked out Elem] (::Array[Elem] ary) -> ::Array[Elem]
[unchecked out Elem] (::int size, ?Elem val) -> ::Array[Elem]
[unchecked out Elem] (::int size) { (::Integer index) -> Elem } -> ::Array[Elem]
Array.new → new_empty_array
Array.new(array) → new_array
Array.new(size, default_value = nil) → new_array
Array.new(size = 0) {|index| ... } → new_array

Returns a new array.

With no block and no argument given, returns a new empty array:

Example
Array.new # => []

With no block and array argument given, returns a new array with the same elements:

Example
Array.new([:foo, 'bar', 2]) # => [:foo, "bar", 2]

With no block and integer argument given, returns a new array containing that many instances of the given default_value:

Example
Array.new(0)    # => []
Array.new(3)    # => [nil, nil, nil]
Array.new(2, 3) # => [3, 3]

With a block given, returns an array of the given size; calls the block with each index in the range (0...size); the element at that index in the returned array is the blocks return value:

Example
Array.new(3)  {|index| "Element #{index}" } # => ["Element 0", "Element 1", "Element 2"]

A common pitfall for new Rubyists is providing an expression as default_value:

Example
array = Array.new(2, {})
array # => [{}, {}]
array[0][:a] = 1
array # => [{a: 1}, {a: 1}], as array[0] and array[1] are same object

If you want the elements of the array to be distinct, you should pass a block:

Example
array = Array.new(2) { {} }
array # => [{}, {}]
array[0][:a] = 1
array # => [{a: 1}, {}], as array[0] and array[1] are different objects

Raises TypeError if the first argument is not either an array or an integer-convertible object). Raises ArgumentError if the first argument is a negative integer.

Related: see Methods for Creating an Array.

See also .[] .try_convert #& also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0