了解范围和数组中的ruby splat

时间:2011-09-26 15:23:38

标签: ruby splat

我正在尝试理解*(1..9)[*1..9]

之间的区别

如果我将它们分配给变量,它们的工作方式相同

splat1 = *(1..9)  # splat1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
splat2 = [*1..9]  # splat2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

但是,当我尝试直接使用*(1..9)[*1..9]时,事情会变得奇怪。

*(1..9).map{|a| a.to_s}  # syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'
[*1..9].map{|a| a.to_s}  # ["1", "2", "3"...]

我猜测问题的一部分是与操作员的预测有关吗?但我不确定发生了什么。为什么我无法使用*(1..9)我可以使用[*1..9]

1 个答案:

答案 0 :(得分:9)

我认为问题在于splat只能用作左值,即它必须被某些东西接收。

因此*(1..9).map的示例失败,因为splat没有收件人,但[*1..9].map有效,因为您创建的数组是splat的收件人。

更新: 关于此主题的更多信息(尤其是最后一条评论):Where is it legal to use ruby splat operator?