红宝石中的函数无效 [英] Invalid function in ruby
问题描述
def request(method ='get',resource,meta = {},strip = true)
end
unexcpected')'expected keyword_end
谢谢!
在Ruby中,带可选参数的参数。使用
def request(resource,method ='get',strip = true,meta = {})
end
将解决此问题。
一个想法实验,考虑原始函数
def request(method ='get',resource,meta = {},strip = true)
end
如果我将该方法称为 request(对象)
,所需行为相当明显 - 用 object
作为资源
参数。但是如果我把它称为 request('post',object)
? Ruby需要理解 method
的语义以决定'post'
是否是方法
或资源
,以及 object
是资源
或 meta
。这超出了Ruby解析器的范围,所以它只是抛出无效的函数错误。
一些附加提示:
我还会把元参数放在最后,它允许您在不加大括号的情况下传递哈希选项,例如:
request(object,'get',true,foo:'bar',bing:'bang')
正如Andy Hayden在评论中指出的那样,以下函数可以工作:
def f (aa,a ='get',b,c);结束
将所有可选参数放在函数末尾以避免心理错误体操需要跟随这样的功能。
Why is this function invalid?
def request(method='get',resource, meta={}, strip=true)
end
unexcpected ')' expecting keyword_end
Thank you!
In Ruby, you can't surround a required parameter with optional parameters. Using
def request(resource, method='get', strip=true, meta={})
end
will solve the issue.
As a thought experiment, consider the original function
def request(method='get',resource, meta={}, strip=true)
end
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.
A couple additional tips:
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')
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.
这篇关于红宝石中的函数无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!