Create Array with Array::new

Download ruby eBook

Example

An empty Array ([]) can be created with Array's class method, Array::new:

Array.new    

To set the length of the array, pass a numerical argument:

Array.new 3 #=> [nil, nil, nil]

There are two ways to populate an array with default values:

  • Pass an immutable value as second argument.
  • Pass a block that gets current index and generates mutable values.
Array.new 3, :x #=> [:x, :x, :x]

Array.new(3) { |i| i.to_s } #=> ["0", "1", "2"]

a = Array.new 3, "X"            # Not recommended.
a[1].replace "C"                # a => ["C", "C", "C"]

b = Array.new(3) { "X" }        # The recommended way.
b[1].replace "C"                # b => ["X", "C", "X"]

Stats

Contributors: 9
2016-11-08
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook