Ruby Operators

From Techotopia
Revision as of 20:16, 18 November 2007 by Neil (Talk | contribs) (Performing Arithmetic using Operators)

Jump to: navigation, search

In this chapter we will cover the basics of perfoming mathematical operations in Ruby.

The Anatomy of a Ruby Math Operation

In Ruby, as with most other programming languages, mathematical operations consist of values on which the calculation is to be performed (called operands) and an operator which dictates the mathematical operation to be performed. Typically, the operands are placed either side of the operator. Optionally, the assignment operator (=) can be used to assign the result of the operation to, for example, a variable. Let's take the most basic of operations, executed in irb:

irb(main):036:0> 1 + 1
=> 2
irb(main):037:0> result = 1 + 1
=> 2

Now let's assign the result to a variable called result:

irb(main):037:0> result = 1 + 1
=> 2

Performing Ruby Arithmetic using Operators

Ruby provides a number of basic operators for performing arithmetic. These are as follows:

OperatorDescription
+Addition - Adds values on either side of the operator
-Subtraction - Subtracts right hand operand from left hand operand
*Multiplication - Multiplies values on either side of the operator
/Division - Divides left hand operand by right hand operand
%Modulus - Divides left hand operand by right hand operand and returns remainder
**Exponent - Peforms exponential calculation on operators