Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Fixnum and Numeric [duplicate]

They seem equivalent, but when comparing them, it's false:

5.is_a? Fixnum
# => true
5.is_a? Numeric
# => true
Numeric == Fixnum
# => false
like image 858
GMarx Avatar asked Dec 19 '22 19:12

GMarx


2 Answers

NUMERIC

Numeric is the class from which all higher-level numeric classes should inherit.

Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as Integer are implemented as immediates, which means that each Integer is a single immutable object which is always passed by value.

FIXNUM

Fixnum 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.

Fixnum objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object.

NOTE: Every Fixnum is Numeric but but every Numeric is not a Fixnum.

UPDATE: Ruby 2.4 unifies fixnum and bignum into integer.

like image 90
techdreams Avatar answered Jan 14 '23 12:01

techdreams


Numeric == Fixnum returns false because they're different classes.

is_a? doesn't check the specific class an object is, that would be instance_of?. This is the documentation for is_a?:

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

As mentioned in the other answer, Fixnum is a subclass of Numeric, this is why 5.is_a? Fixnum and 5.is_a? Numeric both return true.

like image 26
p4sh4 Avatar answered Jan 14 '23 14:01

p4sh4