I would appreciate if someone could explain why the output of this code:
*a, b = [1, 2, 3, 4]
a[b-2] + b
is 7
. Could anyone please break it down line by line so I understand what's going on here? How does this become 7
?
I would appreciate if someone could explain why the output of this code:
*a, b = [1, 2, 3, 4]
a[b-2] + b
is 7
. Could anyone please break it down line by line so I understand what's going on here? How does this become 7
?
To break anything down line by line one could use REPL:
*a, b = [1, 2, 3, 4]
#⇒ [1, 2, 3, 4]
a
#⇒ [1, 2, 3]
b
#⇒ 4
Using splat operator, we have decomposed the original array to new array and the single value. Now everything is crystal clear: a[b-2]
which is a[2]
, which is in turn 3
(check a
array.) and b is still 4
.
3 + 4
#⇒ 7
*a, b = [1, 2, 3, 4]
it means a = [1,2,3]
and b = 4
when you do a[b-2] + b
it will be
+-----------------------+
a[b-2] + b | a[2] |
a[4-2] + 4 | | |
a[2] + 4 | a[1, 2, 3] |
3 + 4 | 0 1 2 -> index |
= 7 +-----------------------+
when you assign array like this,
*a, b = [1, 2, 3, 4]
then it will assign
a = [1,2,3]
and b = 4
Now when you tried to print a[b-2] + b
a[b - 2] = 3
b = 4
3 + 4 = 7
for more understanding use rails console and run line by line.
*a, b = [1, 2, 3, 4]
a
=> [1, 2, 3]
b
=> 4
a[b-2] // b-2 = 2 find value at index of 2 in a, like a[2] is 3
=> 3
a[b-2]+b
=> 7
By using the splat operator on a we are basically letting a to scoop up all the other numbers that b does not need. So b takes one number from the array and a takes everything that is left.
b = 4
a = [1,2,3]
Now when we do this:
a[b-2] + b
It translates into:
a[4-2] + 4
a[2] + 4
Now we check what number is in position 2 in array a.
3 + 4 = 7