Numbers in Ruby Language
Ruby as any other programming language has different classes defined for small to large numbers. However, you don’t need to instantiate numbers all the time as Ruby smart enough to figure out type of the number by looking at it and converting to appropriate type.
Example of such conversion can be demonstrated by calling .class method on different number types such as:
100.class - > Fixnum (small number)
1000000000000.class - > Bignum (large number)
Ruby is smart enough to do proper conversion of the resulting numbers if you try to perform arithmetic command on them. Ruby follows IEEE floating point standard when implementation its own floating numbers.
1.02.class - > Float
Please note that any number type such as Float, Bignum and other inherit from the Number class. Ruby allows number conversions from the string. It simply find first number in the string and converts to it as shown in the examples below
"13 hour of the day".to_i - > 13
'1001 monkeys in the forest’.to_i - > 1001
“3.12”.to_i - > 3
Another way to parse strings for integer is to enclose string within parenthesis of the Integer() or Float() methods such as Float(’99.9% of the gold’). This way of conversion will produce an exception message of conversion is not possible.
Finally, Ruby has BigDecimal numbers which store scientific numbers and they are considered to be the most precise numbers of all number types. It is slower to compare BigDecimal number for instance, but it provided precision which is required by scientific community.
BigDecimal numbers can be split into numbers that make them up. For example,
BigDecimal(‘105000’).split will produce 0.105*(10**6)
BigDecimal numbers allows for precision point calculations as well by applying .precs method on the BigDecimal number such as BigDecimal(“3. 000000000000”).precs -> [9,27]