Ruby Language Arrays Create Array with Array::new

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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

To set the length of the array, pass a numerical argument: 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. 3, :x #=> [:x, :x, :x] { |i| i.to_s } #=> ["0", "1", "2"]

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

b = { "X" }        # The recommended way.
b[1].replace "C"                # b => ["X", "C", "X"]

Got any Ruby Language Question?