From: Phrogz Date: 2007-04-04T22:45:07+09:00 Subject: Re: Everything is a object? On Apr 4, 7:19 am, Jamal Soueidan wrote: > >> if a.nil? > >> p 'thanks'; > >> end > > > Indeed, if a has not been given a value yet, it cannot be "nil" ("nil" > > *is* a value, and an object), so this will fail. > > That made me confused a little bit, How can nil be a class? and then a > method in object base class (nil?) Slim:~ gkistner$ irb irb(main):001:0> a = nil => nil irb(main):002:0> a.class => NilClass irb(main):003:0> nil.class => NilClass irb(main):008:0> NilClass.instance_methods(false) => ["to_s", "|", "to_f", "to_a", "&", "^", "nil?", "to_i", "inspect"] Just like "true" is the literal way to express an instance of the TrueClass and "[]" is the literal way to express an instance of the Array class, "nil" is the literal way to express an instance of the NilClass. That class has methods, like any other. One of those methods is named "nil?". (Not that it makes much difference, but note that "nil?" is a different name from "nil"; the question mark is part of the name.) I say that it doesn't make much difference because you can have method names that are the same as a built-in literal. For example: irb(main):001:0> class Foo irb(main):002:1> def true irb(main):003:2> "maybe" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> f = Foo.new => # irb(main):007:0> puts f.true maybe => nil Heck, lots of built-in classes have a method named "[]", usually used for accessing methods. Indeed, the Array class, which can be instantiated by the literal [], is the primary example of it. So if you write: irb(main):008:0> [][] ArgumentError: wrong number of arguments (0 for 1) from (irb):8:in `[]' from (irb):8 ...what's going on is the first [] instantiate a new array instance, and the second [] call the "[]" method on them...which requires a single argument, hence the error. irb(main):009:0> [ 'a', 'b', 'c', 'd' ][ 2 ] => "c"