Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 569
Ken W Avatar asked May 10 '12 05:05

Ken W


People also ask

Can variable names have question marks?

Bookmark this question. Show activity on this post. A method name can end with a question mark ? but a variable name cannot.

What does question mark mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value). The question mark is a valid character at the end of a method name. https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names.

How do you define a boolean in Ruby?

In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .

What is a Ruby method?

A method in Ruby is a set of expressions that returns a value. Within a method, you can organize your code into subroutines which can be easily invoked from other areas of their program. A method name must start a letter or a character with the eight-bit set.


1 Answers

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 
like image 170
Benjamin Udink ten Cate Avatar answered Sep 28 '22 04:09

Benjamin Udink ten Cate