Array equation explanation

I would appreciate it if anyone could explain why the output of this code is:

*a, b = [1, 2, 3, 4]
a[b-2] + b

there is 7. Can someone break it line by line so that I understand what is going on here? How is it getting 7?

+4
source share
4 answers

To break something line by line, you can use REPL:

*a, b = [1, 2, 3, 4]
#⇒ [1, 2, 3, 4]

a
#⇒ [1, 2, 3]

b
#⇒ 4

Using the splat operator, we decompose the original array into a new array and one value. Now everything is crystal clear: a[b-2]which a[2], which, in turn, 3(check the aarray.), But b still 4.

3 + 4
#⇒ 7
+2
source

*a, b = [1, 2, 3, 4]it means a = [1,2,3]and b = 4when you perform a[b-2] + bit will

                +-----------------------+
a[b-2]   + b    |        a[2]           |
a[4-2]   + 4    |          |            |
a[2]     + 4    |  a[1, 2, 3]           |
3        + 4    |    0  1  2 -> index   |
= 7             +-----------------------+
+2
source

,

*a, b = [1, 2, 3, 4]

a = [1,2,3]

b = 4

, a[b-2] + b

a[b - 2] = 3
b = 4
3 + 4 = 7

rails .

+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 
+2

Source: https://habr.com/ru/post/1680765/


All Articles