Concept Flow - Array creation methods
Start
Choose method
Literal: arr = [
Array.new(size)
Array.new(size, default_value)
Array.new(size) { block }
Array created
Use array
You pick a way to create an array, Ruby builds it, then you use it.
arr1 = [] arr2 = Array.new(3) arr3 = Array.new(3, 0) arr4 = Array.new(3) { |i| i * 2 }
| Step | Action | Code Line | Array State | Notes |
|---|---|---|---|---|
| 1 | Create empty array | arr1 = [] | [] | Empty array with zero elements |
| 2 | Create array with 3 nils | arr2 = Array.new(3) | [nil, nil, nil] | Size 3, default nil |
| 3 | Create array with 3 zeros | arr3 = Array.new(3, 0) | [0, 0, 0] | Size 3, default 0 (same object) |
| 4 | Create array with block | arr4 = Array.new(3) { |i| i * 2 } | [0, 2, 4] | Size 3, values from block using index |
| 5 | End | - | - | All arrays created successfully |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| arr1 | undefined | [] | [] | [] | [] | [] |
| arr2 | undefined | undefined | [nil, nil, nil] | [nil, nil, nil] | [nil, nil, nil] | [nil, nil, nil] |
| arr3 | undefined | undefined | undefined | [0, 0, 0] | [0, 0, 0] | [0, 0, 0] |
| arr4 | undefined | undefined | undefined | undefined | [0, 2, 4] | [0, 2, 4] |
Array creation methods in Ruby:
- Literal: arr = [] creates empty array
- Array.new(size) creates array with nils
- Array.new(size, obj) fills with same obj
- Array.new(size) { block } fills with block values
Use block to avoid shared objects.[] for literals.[] creates an empty array, while {} creates an empty hash, and the other options are not Ruby syntax.Array.new(size, default_value) creates an array with given size and fills it with the default value.Array.new(3, 0) correctly creates [0, 0, 0]. Array.new(0, 3) creates an empty array since size is first argument. Options C and D are invalid syntax.arr = Array.new(4) { |i| i * 2 }
puts arr.inspecti.i * 2: 0*2=0, 1*2=2, 2*2=4, 3*2=6.arr = Array.new(3, []) arr[0] << 1 puts arr.inspect
Array.new(3, []) creates 3 references to the same empty array, not 3 separate arrays.arr[0] << 1 runs, it adds 1 to the shared array, so all elements show the change.Array.new(5, {a: 0, b: 0}) or [{a: 0, b: 0}] * 5 repeats the same hash object 5 times.Array.new(5) { {a: 0, b: 0} } runs the block 5 times, creating 5 separate hashes.Pass the test and this pattern moves unknown