Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid function in ruby

Why is this function invalid?

def request(method='get',resource, meta={}, strip=true)

end

unexcpected ')' expecting keyword_end

Thank you!

like image 549
Al_ Avatar asked Jan 12 '23 13:01

Al_


1 Answers

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.

like image 64
Kyle Avatar answered Jan 21 '23 08:01

Kyle