Search code examples
rubynullfixnum

Can Fixnum/Float be nil?


Can a Fixnum/Float be nil? Like can self even be nil in this case:

class Fixnum
  def clamp(min, max)
    if self == nil then nil end
    ...
  end
end

Solution

  • This is impossible because nil has its own class,NilClass:

    irb(main):001:0> nil.class
    => NilClass
    irb(main):002:0> 456.class
    => Fixnum
    

    So a variable can either be a Fixnum or a NilClass but not both.

    In the context of a class instance method, self always refers to the instance, which is of the type of the class.

    Also self cannot be changed:

    irb(main):006:0> class C
    irb(main):007:1>   def z
    irb(main):008:2>     self = nil
    irb(main):009:2>   end
    irb(main):014:1> end
    SyntaxError: (irb):8: Can't change the value of self
    self = nil
          ^
            from D:/dev/Ruby20/bin/irb:12:in `<main>'