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]

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…