gpt4 book ai didi

ruby - 字符串文字前面的 * 在 ruby​​ 中有什么作用?

转载 作者:数据小太阳 更新时间:2023-10-29 07:11:21 25 4
gpt4 key购买 nike

这段代码似乎创建了一个范围从 a 到 z 的数组,但我不明白 * 的作用。有人可以解释一下吗?

[*"a".."z"]

最佳答案

它叫做 splat operator .

Splatting an Lvalue

A maximum of one lvalue may be splatted in which case it is assigned an Array consisting of the remaining rvalues that lack corresponding lvalues. If the rightmost lvalue is splatted then it consumes all rvalues which have not already been paired with lvalues. If a splatted lvalue is followed by other lvalues, it consumes as many rvalues as possible while still allowing the following lvalues to receive their rvalues.

*a = 1
a #=> [1]

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

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

Empty Splat

An lvalue may consist of a sole asterisk (U+002A) without any associated identifier. It behaves as described above, but instead of assigning the corresponding rvalues to the splatted lvalue, it discards them.

a, *, b = *(1..5)
a #=> 1
b #=> 5

Splatting an Rvalue

When an rvalue is splatted it is converted to an Array with Kernel.Array(), the elements of which become rvalues in their own right.

a, b = *1
a #=> 1
b #=> nil

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

a, b, c = *(1..2), 3
a #=> 1
b #=> 2
c #=> 3

关于ruby - 字符串文字前面的 * 在 ruby​​ 中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4031115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com