Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

Invalid function in ruby

Why is this function invalid?

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

end

unexcpected ')' expecting keyword_end

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...