Question

I was wondering why Ruby names it Fixnum; other languages name it Integer, Int, Number, etc. I saw that Fixnum < Integer and Bignum < Integer, and Integer < Numeric and Float < Numeric. I guess it's because of the size:

1.class => Fixnum
(10**100).class => Bignum

And from the doc:

Holds Integer values that can be represented in a native machine word (minus 1 bit). If any operation on a Fixnum exceeds this range, the value is automatically converted to a Bignum

Why the name Fixnum? I thought about fixed number, but it's not fixed, nor fixed size number.

Était-ce utile?

La solution

This isn't something Ruby came up with — the term "fixnum" comes from Lisp. Just like in Ruby, a fixnum in Lisp is a number that can be represented by a machine integer. Although I've never seen a primary source to prove I'm right, I've always assumed the "fix" part of the name referred to the fact that it can only represent a fixed range of numbers, in contrast with the limitless bignum (which gets its freedom from limits at the expense of worse performance).

Autres conseils

Integer has 2 kinds of children:

Those that can be represented in a native machine word (minus 1 bit): Fixnums. (Check out the object_id of smallish integers. Notice a pattern? Try some other objects, strings, arrays, whatever. That's where the minus 1 bit comes from).

And those which are too large: Bignums (For these an object_id is just like other non-Fixnums.)

p 1.is_a?(Integer) #=> true
p (10**100).is_a?(Integer) #=> true

In Ruby it's an object that has an immediate value. Which basically means that the object is passed rather than the value. So in all honesty it's just the name of the object not really the type.

Read more here: http://www.ruby-doc.org/core-2.1.0/Fixnum.html

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top