I know that the Fixnum
class inherits from the Integer
class. But what is the actual difference between them? Are there any use cases where we sometimes use Fixnum
, and sometimes use Integer
instead?
Ruby – the difference between Integer and Fixnum
ruby
Related Topic
- Ruby-on-rails – How to understand nil vs. empty vs. blank in Ruby
- Ruby – How to sum array of numbers in Ruby
- Ruby-on-rails – Difference between attr_accessor and attr_accessible
- Ruby: kind_of? vs. instance_of? vs. is_a
- Ruby – Difference between map and collect in Ruby
- Ruby, Difference between exec, system and %x() or Backticks
- Ruby – What’s the difference between equal?, eql?, ===, and ==
- Ruby-on-rails – Difference between rake db:migrate db:reset and db:schema:load
Best Answer
UPDATE: As of Ruby 2.4, the
Fixnum
andBignum
classes are gone, there is onlyInteger
. The exact same optimizations still exist, but they are treated as "proper" compiler optimizations, i.e. behind the scenes, invisible to the programmer.This is somewhat confusing.
Integer
is the real class that you should think about.Fixnum
is basically a performance optimization that should never have been made visible to the programmer in the first place. (Compare this with flonums in YARV, which are implemented entirely as an optimization inside the VM, and never exposed to the programmer.)Basically,
Fixnum
s are fast andBignum
s are slow(er), and the implementation automatically switches back and forth between them. You never ask for one of those directly, you will just get one or the other, depending on whether your integer fits into the restricted size of aFixnum
or not.