Cover by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Basic Math Operations

The easiest way to show you the basic math operations is with irb. Fire up irb again and type in some basic expressions, like these:

irb(main):001:0> 7 + 5 # add
=> 12
irb(main):002:0> 20 - 8 # subtract
=> 12
irb(main):003:0> 2 * 6 # multiply
=> 12
irb(main):004:0> 144 / 12 # divide
=> 12
irb(main):005:0> 12**2 # exponent
=> 144
irb(main):006:0> 12 % 5 # modulo (remainder of division)
=> 2

Don't forget the unary operators, + and -, which indicate negative and positive numbers:

irb(main):007:0> +7 + -5
=> 2
irb(main):008:0> -20 + 32
=> 12
irb(main):009:0> -20 - +32
=> −52
irb(main):010:0> 20 * -8
=> −160

If there is no sign immediately before the number, it is positive.

You can also do some of these operations with named methods such as div, modulo, divmod, quo, and remainder. Method calls are shown with integer, float, and parentheses so you can see the differences they make.

irb(main):011:0> 24.div 2 # division
=> 12
irb(main):012:0> (25.0).div(2.0) # result is integer
=> 12
irb(main):013:0> 12.modulo 5 # modulo
=> 2
irb(main):014:0> 12.modulo(5.0) # modulo with float
=> 2.0
irb(main):015:0> 12.divmod 5 # return array with quotient, modulus
=> [2, 2]
irb(main):016:0> 12.0.divmod 5.0 # with float
=> [2, 2.0]
irb(main):017:0> 12.quo 5 # return the quotient
=> 2.4
irb(main):018:0> 12.remainder 5 # return the remainder
=> 2

Many of these methods started life as methods of the Numeric class, but were overridden or redefined in other subclasses. You will find versions ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required