【发布时间】:2017-01-31 21:54:28
【问题描述】:
我现在正在学习 Ruby,遇到了这种特殊情况。
当我运行以下代码时,我会得到下面进一步显示的输出。
工作代码:
def hello(a,b=1,*c,d,e,f)
p a,b,c,d,e,f
end
hello(1,2,3,4,5)
工作代码输出:
1
2
[]
3
4
5
但是,在编辑代码以使参数“e”成为捕获所有参数时,我得到了下面进一步显示的错误。
失败代码:
def hello(a,b=1,c,d,*e,f)
p a,b,c,d,e,f
end
hello(1,2,3,4,5)
失败的代码输出:
a.rb:1: syntax error, unexpected *
def hello(a,b=1,c,d,*e,f)
^
a.rb:1: syntax error, unexpected ')', expecting '='
a.rb:3: syntax error, unexpected keyword_end, expecting end-of-input
我在 Ubuntu 上使用 ruby 2.3.1p112(2016-04-26 修订版 54768)。
我很想知道为什么第二个 sn-p 代码会失败。
编辑:
以下代码也失败了。
def hello(a,b=1,c,d,e,*f)
p a,b,c,d,e,f
end
hello(1,2,3,4,5)
我得到一个类似的错误
a.rb:1: syntax error, unexpected *
def hello(a,b=1,c,d,e,*f)
^
a.rb:3: syntax error, unexpected keyword_end, expecting end-of-input
【问题讨论】:
-
在末尾使用 splat 运算符对我来说没有意义。
-
是的。它不可读,但可以解析它,Ruby 在某些情况下会这样做。
-
@fl00r 我尝试了以下方法定义,但我得到了同样的错误。 def hello(a,b=1,c,d,e,*f)
标签: ruby