Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array equation explanation

Tags:

ruby

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?

like image 395
Twistedben Avatar asked Jan 04 '23 18:01

Twistedben


1 Answers

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
like image 89
Aleksei Matiushkin Avatar answered Jan 13 '23 10:01

Aleksei Matiushkin