LaunchKit
All quizzes
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

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"
  1. numbers[1, 0] = [4] targets the slice that starts at index 1 and spans 0 elements: an empty slot between 1 and 2.
  2. The elements of the right-hand array are inserted there. Note that [4] is unpacked: the array gains the element 4, not a nested [4].
  3. 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.

Only used to confirm and publish your comment. Never shown publicly, never shared.

Markdown: **bold**, `code`, ```fenced blocks```, > quotes, [links](url). HTML and images are not rendered.