Sobes.tech
Intern

What is Array.new in Ruby?

sobes.tech AI

Answer from AI

Array.new is a method of the Array class for creating new array objects. It has several overloads.

  1. Without arguments: Creates an empty array.
    # Creates []
    Array.new
    
  2. With one argument (size): Creates an array of the specified size, filled with nil.
    # Creates [nil, nil, nil]
    Array.new(3)
    
  3. With two arguments (size, default value): Creates an array of the specified size, initialized with the given value. Important: if the value is a mutable object (like another array or hash), all elements will reference the same object.
    # Creates [1, 1, 1]
    Array.new(3, 1)
    
    # Caution: creates [[], [], []], but all inner arrays are the same object
    arr = Array.new(3, [])
    arr[0] << 1
    # arr now [[1], [1], [1]]
    
  4. With one argument (size) and a block: Creates an array of the specified size, where each element is initialized with the result of executing the block. The index of the element is passed to the block as an argument. This approach allows creating an array with unique mutable objects.
    # Creates [0, 1, 4] (index squared)
    Array.new(3) { |i| i * i }
    
    # Creates [[], [], []] with unique inner arrays
    arr = Array.new(3) { [] }
    arr[0] << 1
    # arr now [[1], [], []]