Search code examples
rubymathintegerfixnum

How can I force Ruby numbers to behave like integers, not fixnums?


I have:

steven$ irb
ruby-1.9.2-p180 :001 > foo = "256MB"
 => "256MB" 
ruby-1.9.2-p180 :002 > interim_result = foo.slice(/\d+/).to_i
 => 256 
ruby-1.9.2-p180 :003 > interim_result.class
 => Fixnum 
ruby-1.9.2-p180 :004 > result = interim_result/1028
 => 0 

I want result to be 0.25. How can I make this happen?

Is it necessary/possible to force interim_result.class to be integer?

Please note the following doesn't give the desired result of 0.25:

ruby-1.9.2-p180 :002 > interim_result = foo.slice(/\d+/).to_f
 => 256.0 
ruby-1.9.2-p180 :003 > result = interim_result/1028
 => 0.2490272373540856 
ruby-1.9.2-p180 :004 > result.round_to(2)
NoMethodError: undefined method `round_to' for 0.2490272373540856:Float

Thanks.


Solution

  • Yes, the easiest way would be to call to_f instead of to_i when assigning a value to interim_result.