4

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Twistedben
  • 111
  • 9

5 Answers5

2

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
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • So the * operator splits the array at the end and assigns it the last indexed value? And by that, I mean why does *a take the first 3 indexed values and b the last, 4? – Twistedben Jul 05 '17 at 06:14
  • 1
    Nope, the splat operator assigns the array on the right to the operand, comma is what decomposes (splits) the original array. – Aleksei Matiushkin Jul 05 '17 at 06:17
  • [This answer](https://stackoverflow.com/questions/18289152/what-does-a-double-splat-operator-do#18289216) is the great source to demistify the splat [and double splat] operator. – Aleksei Matiushkin Jul 05 '17 at 06:18
2

*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             +-----------------------+
Vivek
  • 859
  • 7
  • 11
2

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.

Hardik Upadhyay
  • 2,639
  • 1
  • 19
  • 34
2
*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 
Mayur Shah
  • 3,344
  • 1
  • 22
  • 41
1

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
Ionut Ticus
  • 2,683
  • 2
  • 17
  • 25
VeronikaS
  • 151
  • 4