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?
Bookmark this question. Show activity on this post. A method name can end with a question mark ? but a variable name cannot.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With