问题描述
我喜欢括号中的方法参数,这是对Pascal的怀旧.清理代码时,如果我发现没有它的方法参数,则会立即将它们括起来.今天,尽管根据文档,我的语法看起来还不错,但它却导致了我的工作代码抛出错误.
I like method parameters enclosed in parenthesis, this is some Pascal nostalgia. When cleaning up code, if I find a method parameters without it I enclose them immediately.Today it caused my working code throwing errors although my syntax looks okay according to the documentation.
Kernel.raise的文档具有以下格式:
Kernel.raise's documentation has this format:
(Object) raise(exception[, string [, array]])
这些都可以正常工作
> raise TypeError
TypeError: TypeError
> raise (TypeError)
TypeError: TypeError
> raise "Error message"
RuntimeError: Error message
> raise ("Error message")
RuntimeError: Error message
但是下一个附带的版本引发语法错误:
But the enclosed version of the next throws syntax error:
> raise TypeError, "Error message"
TypeError: Error message
> raise (TypeError, "Error message")
SyntaxError: unexpected ')', expecting $end
我可以没有它,我只想知道为什么会以错误结束.
I can live without it, I just want to know why this ends with an error.
推荐答案
您可能已经知道,在惯用的Ruby中,永远不会在方法的末尾与括号中的参数列表之间插入空格. 某些样式指南明确禁止使用.
You probably already know that in idiomatic Ruby one would never insert a space between the end of a method and an argument list in parenthesis. Some style guides explicitly forbid it.
还有一个务实的理由.
1.9.2-p290 > def concat(a, b)
1.9.2-p290 > a + b
1.9.2-p290 > end
1.9.2-p290 > concat 'foo', 'bar'
=> "foobar"
1.9.2-p290 > concat('foo', 'bar')
=> "foobar"
1.9.2-p290 > concat ('foo', 'bar')
SyntaxError: (irb):27: syntax error, unexpected ',', expecting ')'
以这种方式调用任何方法都会遇到错误,而不仅仅是Kernel.raise
.
You'll encounter errors calling any method this way, not just Kernel.raise
.
我对Ruby内部并不熟悉,但是我可以想象这是因为当参数列表之前有一个空格时,Ruby期望使用无括号"样式.因此,这当然有效:
I'm not familiar with Ruby internals, but I would imagine the reason for this is that when a space precedes the argument list, Ruby is expecting the "no-parens" style. So of course this works:
1.9.2-p290 :035 > concat ("bar"), ("foo")
=> "barfoo"
大概是Ruby在将结果传递给方法之前尝试评估每个带括号的表达式的内容.我推测写raise (TypeError, "Error message")
是要Ruby评估TypeError, "Error message"
,这当然会失败.
Presumably Ruby is trying to evaluate the contents of each parenthesized expression before passing the result to the method. I'd speculate that writing raise (TypeError, "Error message")
is asking Ruby to evaluate just TypeError, "Error message"
, which of course fails.
这篇关于将参数括在括号中时,Ruby Kernel.raise方法会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!