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
281 views
in Technique[技术] by (71.8m points)

ruby - Should a method ending in ? (question mark) return only a boolean?

I think it's just common sense and Ruby convention to do this but I have this method:

def is_subscribed?(feed_url)
  Subscription.find_by_user_id_and_feed_id(self[ :id ], Feed.find_by_feed_url(feed_url))
end

The only confusion I'm getting is, this doesn't return boolean like I originally anticipated by putting the question mark on the end of the method name. I was under the impression that when evaluating an object as conditional it returns true if not nil.

Apparently I'm missing the point here and it's not evaluating it like I thought.

So, my question is, would it be best to just do an if (condition) true else false? Or is there a more elegant method of doing this?

question from:https://stackoverflow.com/questions/10527997/should-a-method-ending-in-question-mark-return-only-a-boolean

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

1 Reply

0 votes
by (71.8m points)

A method ending with ? should return a value which can be evaluated to true or false. If you want to ensure a boolean return, you can do so by adding a double bang to the finder.

def is_subscribed?(feed_url)
  !!Subscription.find_by_user_id_and_feed_id(self[ :id ], Feed.find_by_feed_url(feed_url))
end

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

...