From: Robert Klemme Date: 2010-08-15T19:35:13+09:00 Subject: Re: kind_of?( NilClass ) On 14.08.2010 22:02, Philipp Kempgen 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 -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/