Zack Shapiro
Zack Shapiro

Reputation: 6998

Why is my string converting into a Fixnum when using .to_i rather than an integer?

I'm running this line:

<%= @date[i].created_at.strftime('%d').to_i.class %>

and the output is a fixnum rather than an int. Why is this?

From the controller:

@date = Lesson.find(:all, :order => 'created_at ASC')

Upvotes: 1

Views: 1098

Answers (2)

Niklas B.
Niklas B.

Reputation: 95358

There's no such thing int in Ruby. Fixnum is the class of small numbers like 1 or 2 that fit into a machine word, and it's a subclass of Integer. Check the following:

irb(main):004:0> 42.class
=> Fixnum
irb(main):005:0> 42.is_a? Fixnum
=> true
irb(main):006:0> 42.is_a? Integer
=> true
irb(main):007:0> 42.is_a? Numeric
=> true
irb(main):008:0> 42.is_a? Object
=> true

So your value is a Fixnum, an Integer, a Numeric and an Object at the same time ;) This effect is called polymorphism and it might surprise you in this context because in some other programming languages numbers are treated in a special way (they have some kind of "native" type). In Ruby, numbers are just objects.

Upvotes: 6

pdu
pdu

Reputation: 10423

A 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 is, in fact, a child class of Integer.

See http://www.ruby-doc.org/core-1.9.3/Integer.html

Upvotes: 1

Related Questions