kind_of?( NilClass )

P

Philipp Kempgen

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
 
D

David Masover

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.
 
P

Philipp Kempgen

David Masover schrieb (am 15.8.10 07:58):
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.

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
 
R

Robert Klemme

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 `<main>'
irb(main):002:0> NilClass.allocate
TypeError: allocator undefined for NilClass
from (irb):2:in `allocate'
from (irb):2
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top