Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am not experienced in Ruby, so my code feels "ugly" and not idiomatic:

def logged_in?   !user.nil? end 

I'd rather have something like

def logged_in?   user.not_nil? end 

But cannot find such a method that opposites nil?

like image 991
berkes Avatar asked Oct 25 '10 08:10

berkes


People also ask

What does != nil in Ruby mean?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.

Is nil the same as null Ruby?

nil is an Object, NULL is a memory pointer Sadly, when this happens, Ruby developers are confusing a simple little Ruby object for something that's usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0.

How do you check if something is not nil in Ruby?

That's the easy part. In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

Is nil empty Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.


1 Answers

You seem overly concerned with booleans.

def logged_in?   user end 

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 
like image 70
Samo Avatar answered Sep 18 '22 17:09

Samo