Ruby
0 views
Inserting with numbers[1, 0] = [4]
Question
What's the return value of this Ruby 3 code?
numbers = [1, 2, 3]
numbers[1, 0] = [4]
numbers.join("x") # => ???
The correct answer is
-
"1x4x2x3"Correct -
"4x1x2x3" -
"5x2x3" -
It raises
SyntaxError
Explanation
TL;DR
numbers[start, length] = replacement replaces length elements beginning at start with the elements of replacement. With length zero, nothing is removed and the new elements are spliced in at index 1, so the array becomes [1, 4, 2, 3] and join("x") returns "1x4x2x3".
Step by step
numbers = [1, 2, 3]
numbers[1, 0] = [4]
numbers # => [1, 4, 2, 3]
numbers.join("x") # => "1x4x2x3"
numbers[1, 0] = [4]targets the slice that starts at index1and spans0elements: an empty slot between1and2.- The elements of the right-hand array are inserted there. Note that
[4]is unpacked: the array gains the element4, not a nested[4]. join("x")concatenates the elements with"x"between them.
The full Array#[]= splice family
The same form replaces and deletes, depending on length and the replacement:
numbers = [1, 2, 3]
numbers[2, 1] = [9] # replace 1 element at index 2
numbers # => [1, 2, 9]
numbers = [1, 2, 3]
numbers[1, 2] = [] # delete 2 elements at index 1
numbers # => [1]
numbers = [1, 2, 3]
numbers[1..2] = [9] # range form: replace indices 1..2
numbers # => [1, 9]
Because the right-hand array is unpacked, inserting an actual array as one element requires wrapping it once more:
numbers = [1, 2, 3]
numbers[1, 0] = [[4]]
numbers # => [1, [4], 2, 3]
The idiomatic spelling
For a pure insertion, Array#insert says what it means:
[1, 2, 3].insert(1, 4) # => [1, 4, 2, 3]
numbers[1, 0] = [4] earns its place when you are already thinking in slices, for example replacing a variable-length window in one assignment.
Share this quiz
Comments
No comments yet. Be the first.