Is there a Ruby, or Ruby-ism for not_nil? opposite of nil? method? Is there a Ruby, or Ruby-ism for not_nil? opposite of nil? method? ruby-on-rails ruby-on-rails

Is there a Ruby, or Ruby-ism for not_nil? opposite of nil? method?


You seem overly concerned with booleans.

def logged_in?  userend

If the user is nil, then logged_in? will return a "falsey" value. Otherwise, it will return an object. In Ruby we don't need to return true or false, since we have "truthy" and "falsey" values like in JavaScript.

Update

If you're using Rails, you can make this read more nicely by using the present? method:

def logged_in?  user.present?end


when you're using ActiveSupport, there's user.present? http://api.rubyonrails.org/classes/Object.html#method-i-present%3F, to check just for non-nil, why not use

def logged_in?  user # or !!user if you really want boolean'send


Beware other answers presenting present? as an answer to your question.

present? is the opposite of blank? in rails.

present? checks if there is a meaningful value. These things can fail a present? check:

"".present? # false"    ".present? # false[].present? # falsefalse.present? # falseYourActiveRecordModel.where("false = true").present? # false

Whereas a !nil? check gives:

!"".nil? # true!"    ".nil? # true![].nil? # true!false.nil? # true!YourActiveRecordModel.where("false = true").nil? # true

nil? checks if an object is actually nil. Anything else: an empty string, 0, false, whatever, is not nil.

present? is very useful, but definitely not the opposite of nil?. Confusing the two can lead to unexpected errors.

For your use case present? will work, but it's always wise to be aware of the difference.