views:

88

answers:

4

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
  user.not_nil?
end

But cannot find such a method that opposites nil?

A: 

Maybe this could be an approach:

class Object
  def not_nil?
    !nil?
  end
end
Geo
Good idea. I make from this that there is no not_nil? in Ruby. But should this not be `!self.nil?` rather then `!nil?`, or is `self`implicit?
berkes
You don't need self. It will be implied.
Geo
A: 

You can just use the following:

if object
  p "object exists"
else
  p "object does not exist"
end

This does not only work for nil but also false etc, so you should test to see if it works out in your usecase.

Bitterzoet
+2  A: 

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
end
lwe
I added a tag to my original post, indicating that -indeed- I am using Rails, hence the user.present? is present. AFAIK that indeed is the exact opposite of nil? Hence exactly what I need (in this context, a rails project)
berkes
A: 

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.

Samo