如何使用ruby splat运算符?我们能对它做一些操作吗?

时间:2021-12-26 00:11:09

The confusing case:

令人困惑的案例:

arr = [:one, :two]
attr_accessor *arr + [:three]

In this case, it seems that we do a + operation on the splat *arr. But, generally we can't perform any operation on splat. So this make me confused.

在这种情况下,似乎我们对splat * arr进行了+操作。但是,通常我们不能对splat执行任何操作。所以这让我很困惑。

I prefer another case like this:

我更喜欢这样的另一个案例:

arr = [:one, :two]
attr_accessor *(arr << :three)

So, what's your opinion?

那么,你有什么看法?

1 个解决方案

#1


No, you got the precedence wrong. *arr + [:three] is *(arr + [:three]), so it splats three arguments onto attr_accessor. The result of a splat is not a Ruby value, so no operations can be done on it. It is not an operator in the same sense that + is operator. Whereas + is a method, this usage of * is not.

不,你的优先权是错的。 * arr + [:three]是*(arr + [:three]),所以它将三个参数splat到attr_accessor上。 splat的结果不是Ruby值,因此无法对其执行任何操作。它不是一个与运算符相同的运算符。而+是一种方法,*的这种用法不是。

(There is no opinion here, only a fact on how Ruby works.)

(这里没有任何意见,只有关于Ruby如何工作的事实。)

#1


No, you got the precedence wrong. *arr + [:three] is *(arr + [:three]), so it splats three arguments onto attr_accessor. The result of a splat is not a Ruby value, so no operations can be done on it. It is not an operator in the same sense that + is operator. Whereas + is a method, this usage of * is not.

不,你的优先权是错的。 * arr + [:three]是*(arr + [:three]),所以它将三个参数splat到attr_accessor上。 splat的结果不是Ruby值,因此无法对其执行任何操作。它不是一个与运算符相同的运算符。而+是一种方法,*的这种用法不是。

(There is no opinion here, only a fact on how Ruby works.)

(这里没有任何意见,只有关于Ruby如何工作的事实。)