Sobes.tech
Middle

Why pass a block during array initialization?

sobes.tech AI

Answer from AI

When initializing an array with Array.new(size, &block) or Array.new(size) { ... }, the block is used to dynamically determine the value of each element. Without a block, if only the size is specified, all elements are initialized to nil. If an initial value is provided, all elements will reference the same object.

Advantages of using a block:

  • Dynamic initialization: Each element is initialized with an independent value, which can depend on its index.
  • Creating unique objects: If array elements need to be unique objects (e.g., arrays, hashes, or class instances), the block creates a new object for each element, instead of all elements referencing the same object.

Example:

# Initialization with nil
arr1 = Array.new(3)
# => [nil, nil, nil]

# Initialization with a fixed value (one object)
arr2 = Array.new(3, [])
arr2[0] << 1
# => [[1], [1], [1]] # Expected [[1], [], []], but all elements changed

# Initialization with a block (unique objects)
arr3 = Array.new(3) { [] }
arr3[0] << 1
# => [[1], [], []] # Expected behavior

The block takes an argument — the index of the current array element, allowing creation of elements dependent on their position:

arr4 = Array.new(5) { |index| index * 2 }
# => [0, 2, 4, 6, 8]

Using a block during array initialization is a flexible way to create an array with arbitrary, often unique, initial values for each element.