477 views
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"
"4x1x2x3"
"5x2x3"
It raises SyntaxError
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
Let's dive deeper into the Ruby Array#[]=
method and how it behaves in this particular example.
The Array#[]=
method in Ruby is used to assign a value to a specific position (or range) within an array.
The syntax can be quite versatile, allowing you to replace elements, insert new elements, or even delete elements depending on the parameters provided.
Here’s a breakdown of the syntax:
array[index] = value
Let's analyze the given code step by step:
numbers = [1, 2, 3] numbers[1, 0] = [4] numbers.join("x") # => "1x4x2x3"
Initial Array Setup
numbers = [1, 2, 3]
.1
, 2
, and 3
.Array Insertion with Array#[]=
numbers[1, 0] = [4]
uses a somewhat unusual but powerful feature of the Array#[]=
method.1
is the index where we want to start the insertion, and 0
is the number of elements to be replaced.[4]
is the value being inserted.So, what happens here?
numbers[1, 0] = [4]
tells Ruby to insert [4]
at index 1
without removing any existing elements.0
after the index 1
indicates that no elements should be removed. Instead, the new element [4]
is inserted at that position.numbers
is modified to [1, 4, 2, 3]
.Joining Array Elements
numbers.join("x")
method is called.join
method combines all the elements of the array into a single string, with "x"
as the separator between elements."1x4x2x3"
.Array#[]=
method can be used not just to replace elements but also to insert new elements without removing any existing ones.0
) indicates how many elements should be removed, allowing for flexibility in modifying arrays.Let’s expand this with a few more variations to see how the Array#[]=
method works in different scenarios:
numbers = [1, 2, 3, 5] # Insert 4 at index 3 (before 5) numbers[3, 0] = [4] numbers # => [1, 2, 3, 4, 5] # Replace the element at index 2 with 9 numbers[2, 1] = [9] numbers # => [1, 2, 9, 4, 5]
In summary, the Array#[]=
method is extremely versatile, allowing for a wide range of operations including insertion, replacement, and removal of elements within an array.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©