1

在 ruby​​ 中,可以将多个赋值与 splat 运算符结合起来,以模拟函数式语言中的 first 和 rest(或 head 和 tail)。

first, *rest = [1,2,3,4]  
first # output: 1
rest # output: [2,3,4]

splat 操作员是如何实现这一点的?

4

1 回答 1

4

在多重赋值中最多可以有一个 splat 运算符,splat 运算符将调整数组的长度以完全匹配右侧的内容。换句话说:

1)当左边的变量个数大于右边数组的长度时,带splat的变量会被赋值为一个空数组:

*a = []
# => a == []

*a, b = [1]
# => a == [], b == 1

a, *b = [1]
# => a == 1, b == []

*a, b, c = [1, 2]
# => a == [], b == 1, c == 2

a, *b, c = [1, 2]
# => a == 1, b == [], c == 2

a, b, *c = [1, 2]
# => a == 1, b == 2, c == []

...

2) 否则,带有 splat 的变量将扩展以填充右侧的其余元素:

*a = [1, 2]
# => a == [1, 2]

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

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

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

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

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

....
于 2012-12-30T19:49:48.207 回答