Kind_of?( NilClass )

Should I write
var.kind_of?( NilClass )
or simply
var == nil
?

I have the feeling that kind_of?(NilClass) is more “proper”/“clean”
but then again it decreases the readability and might not even be
necessary.

Are there any situations where it makes sense to subclass NilClass?

Regards,
Philipp

You can always var.nil?

Steve K. wrote:

You can always var.nil?

Well, yes if the var is a kind_of?(Object) but not if
it’s just a BasicObject.

Regards,
Philipp

On Aug 14, 2010, at 1:02 PM, Philipp K. [email protected] wrote:

Should I write
var.kind_of?( NilClass )
or simply
var == nil

Do you actually care if it is nil? Or just untruthy? I much prefer

not var

On Saturday, August 14, 2010 03:10:28 pm Philipp K. wrote:

Steve K. wrote:

You can always var.nil?

Well, yes if the var is a kind_of?(Object) but not if
it’s just a BasicObject.

The purpose of a BasicObject is, generally, to implement proxy classes.
Presumably, this would send a nil? through to whatever you were
proxying,
right?

Also, I don’t see a kind_of? on BasicObject, either, so calling pretty
much
anything on var would fail.

David M. schrieb (am 15.8.10 07:58):

Also, I don’t see a kind_of? on BasicObject, either, so calling pretty much
anything on var would fail.

Right.

I guess I’ll stick with
! var
or
not var
which is what Ryan suggested and which is about twice as fast as
any one of
! var.nil?()
! var.eql?(nil)
! nil.eql?(var)
! var.kind_of?(NilClass)

Regards,
Philipp

On 14.08.2010 22:02, Philipp K. wrote:

Should I write
var.kind_of?( NilClass )
or simply
var == nil
?

I have the feeling that kind_of?(NilClass) is more “proper”/“clean”
but then again it decreases the readability and might not even be
necessary.

The other suggested checks are cleaner IMHO. There is only ever one
instance of NilClass (see below) so you can immediately check against
that or use method #nil?.

You cannot create other instances:

irb(main):001:0> NilClass.new
NoMethodError: undefined method new' for NilClass:Class from (irb):1 from /usr/local/bin/irb19:12:in
irb(main):002:0> NilClass.allocate
TypeError: allocator undefined for NilClass
from (irb):2:in allocate' from (irb):2 from /usr/local/bin/irb19:12:in
irb(main):003:0>

Are there any situations where it makes sense to subclass NilClass?

Unlikely.

So, in an attempt to sum this up. This is what you can do ordered from
what I’d consider most reasonable to least reasonable:

if var.nil? # test for identity
if var == nil # test for equivalence
if var.equal? nil # test for identity
unless var # note: will also catch false
if NilClass === var # superfluous type check
if var.kind_of? NilClass # superfluous type check

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs