Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...