在哪里使用 ruby​​ splat 运算符是合法的? [英] Where is it legal to use ruby splat operator?

查看:42
本文介绍了在哪里使用 ruby​​ splat 运算符是合法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Splats 很酷.它们不仅用于爆炸数组,尽管这很有趣.他们还可以转换为 Array 和展平数组(参见 http://github.com/mischa/splat/tree/master 获取他们所做工作的详尽列表.)

Splats are cool. They're not just for exploding arrays, although that is fun. They can also cast to Array and flatten arrays (See http://github.com/mischa/splat/tree/master for an exhaustive list of what they do.)

看起来无法对 splat 执行其他操作,但在 1.8.6/1.9 中,以下代码抛出意外的 tSTAR":

It looks like one cannot perform additional operations on the splat, but in 1.8.6/1.9 the following code throws "unexpected tSTAR":

foo = bar ||*zap #=>意外的tSTAR

虽然这有效:

foo = *zap ||栏#=>有效,但价值有限

splat 可以出现在表达式中的什么位置?

Where can the splat appear in an expression?

推荐答案

首先,这里的优先级不是问题,因为 foo = bar ||(*zap) 效果也不好.一般的经验法则是您不能在 splat 上执行额外的操作.即使像 foo = (*zap) 这样简单的东西也是无效的.这也适用于 1.9.

First, precedence isn't an issue here, because foo = bar || (*zap) works no better. The general rule of thumb is that you cannot perform additional operations on a splat. Even something as simple as foo = (*zap) is invalid. This applies to 1.9 as well.

说了这么多,你还有什么期待 foo = bar ||*zap 去做,如果它有效,那就不同于 foo = bar ||击中?即使在像 a, b = bar || 这样的情况下*zap(也不起作用),a, b = bar ||zap 完成了我认为是相同的事情.

Having said that, what do you expect foo = bar || *zap to do, if it worked, that is different than foo = bar || zap? Even in a case like a, b = bar || *zap (which also doesn't work), a, b = bar || zap accomplishes what I'd assume would be the same thing.

唯一可能有意义的情况是 a, b = foo, bar ||*zap.您应该会发现,a, b = foo, *(bar || zap) 涵盖了您想要使用它的大多数情况.如果这不能涵盖您的情况,您可能应该问问自己,通过编写如此丑陋的构造,您真正希望实现什么.

The only situation where this might make any sense is something like a, b = foo, bar || *zap. You should find that most cases where you would want to use this are covered by a, b = foo, *(bar || zap). If that doesn't cover your case, you should probably ask yourself what you really hope to accomplish by writing such an ugly construct.

回应您的评论,*zap ||bar 等价于 *(zap || bar).这表明 splat 的优先级有多低.到底有多低?我能给你的最佳答案是相当低".

In response to your comments, *zap || bar is equivalent to *(zap || bar). This demonstrates how low the splat's precedence is. Exactly how low is it? The best answer I can give you is "pretty low".

不过,举一个有趣的例子,考虑一个方法 foo,它接受三个参数:

For an interesting example, though, consider a method foo which takes three arguments:

def foo(a, b, c)
  #important stuff happens here!
end

foo(*bar = [1, 2, 3]) 将在赋值后执行并将参数分别设置为 1、2 和 3.将其与 foo((*bar = [1, 2, 3])) 进行比较,后者会抱怨参数数量错误(1 代表 3).

foo(*bar = [1, 2, 3]) will splat after the assignment and set the arguments to 1, 2, and 3 respectively. Compare that with foo((*bar = [1, 2, 3])) which will complain about having the wrong number of arguments (1 for 3).

这篇关于在哪里使用 ruby​​ splat 运算符是合法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆