ruby 中的无效函数 [英] Invalid function in ruby
问题描述
为什么这个函数无效?
def request(method='get',resource, meta={}, strip=true)
end
意外的 ')' 期待 keyword_end
unexcpected ')' expecting keyword_end
谢谢!
推荐答案
在 Ruby 中,不能用可选参数包围必需参数.使用
In Ruby, you can't surround a required parameter with optional parameters. Using
def request(resource, method='get', strip=true, meta={})
end
将解决问题.
作为一个思想实验,考虑原始函数
As a thought experiment, consider the original function
def request(method='get',resource, meta={}, strip=true)
end
如果我将该方法称为request(object)
,则所需的行为是相当明显的——以object
作为resource
调用该方法> 参数.但是如果我把它称为 request('post', object)
呢?Ruby 需要理解 method
的语义来决定 'post'
是 method
还是 resource
,以及 object
是 resource
还是 meta
.这超出了 Ruby 解析器的范围,因此它只会抛出无效函数错误.
If I call that method as request(object)
, the desired behavior is fairly obvious -- call the method with object
as the resource
parameter. But what if I call it as request('post', object)
? Ruby would need to understand the semantics of method
to decide whether 'post'
is the method
or the resource
, and whether object
is the resource
or the meta
. This is beyond the scope of Ruby's parser, so it simply throws an invalid function error.
一些额外的提示:
我也会把 meta 参数放在最后,它允许你在没有花括号的情况下传递哈希选项,例如:
I would also put the meta argument last, which allows you to pass the hash options in without curly braces, such as:
request(object, 'get', true, foo: 'bar', bing: 'bang')
正如 Andy Hayden 在评论中指出的那样,以下函数有效:
As Andy Hayden pointed out in the comments, the following function works:
def f(aa, a='get', b, c); end
将所有可选参数放在函数的末尾通常是一种很好的做法,以避免在调用此类函数时产生心理体操.
It's generally good practice to place all your optional parameters at the end of the function to avoid the mental gymnastics required to follow calls to a function like this.
这篇关于ruby 中的无效函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!