What does this mean in Ruby language?

后端 未结 3 1957
孤城傲影
孤城傲影 2021-01-06 01:05

Run the following code,

a = [1, 2, 3, 4, 5]
head, *tail = a
p head
p tail

You will get the result

1
[2, 3, 4, 5]

3条回答
  •  猫巷女王i
    2021-01-06 01:28

    First, it is a parallel assignment. In ruby you can write

    a,b = 1,2
    

    and a will be 1 and b will be 2. You can also use

    a,b = b,a
    

    to swap values (without the typical temp-variable needed in other languages).

    The star * is the pack/unpack operator. Writing

    a,b = [1,2,3]
    

    would assign 1 to a and 2 to b. By using the star, the values 2,3 are packed into an array and assigned to b:

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

提交回复
热议问题