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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With