Blog
Ruby Programming Series Chapter 3 Numbers
- February 17, 2017
- Posted by: admin
- Category: Uncategorized

While working with numbers in ruby, there are only 2 classes that the values belong to. One will be a Fixnum class and other would be a Float class. Any value either positive or negative integer belong to Fixnum class and if the value has a decimal point it belongs to Float class
Given below are few variables assigned to numbers
num1 = 10 num2 = 12.8 num3 = 18.2 num4 = 2
We can see that
num1.class # returns Fixnum num2.class # returns Float
When we use numbers in a program, we generally perform arithmetic operations of them. All the regular arithmetic operators can be used on numbers in ruby like the +, -, / ,* & %
Here (+) is for addition, (-) is for subtraction, (*) is for multiplication,( /) is for division, (%) is known as a modulo operator, when modulo operator is used it returns the remainder ie.
10 % 3 # gives us 1
num1 + num4 => 12 num2 + num3 => 31 num2 – num1 => 2.8 num1 / num2 => 2 num1 * num2 => 20
Number Methods
num2.round # 13 Num3.round # 18 Num3.ceil # 19 Num2.floor # 12 (-123).abs # 123 abs returns the absolute value Type conversions in Ruby num1.to_f # 10.0 num2.to_i # 12 Num3.to_s # “18.2” Num1.odd? # false Num1.even? # true
( note – any method ending with ? is known as a Boolean method in ruby, the return value will always either true or false )