在 Ruby 中,不能用可选参数包围必需参数。使用
def request(resource, method='get', strip=true, meta={})
end
将解决问题。
作为一个思想实验,考虑原始函数
def request(method='get',resource, meta={}, strip=true)
end
如果我将该方法称为request(object)
,所需的行为是相当明显的 - 调用该方法object
as the resource
范围。但如果我把它称为request('post', object)
? Ruby 需要理解以下语义method
来决定是否'post'
is the method
or the resource
,以及是否object
is the resource
or the meta
。这超出了 Ruby 解析器的范围,因此它只是抛出一个无效函数错误。
一些额外的提示:
我还将元参数放在最后,它允许您在不使用大括号的情况下传递哈希选项,例如:
request(object, 'get', true, foo: 'bar', bing: 'bang')
正如 Andy Hayden 在评论中指出的,以下函数有效:
def f(aa, a='get', b, c); end
通常最好的做法是将所有可选参数放在函数末尾,以避免调用此类函数所需的心理体操。