Ruby Operators

From Techotopia
Revision as of 21:16, 18 November 2007 by Neil (Talk | contribs) (Operator Precedence)

Jump to: navigation, search

In this chapter we will cover the basics of using operators in Ruby to build expressions. Ruby provides a number of different types of operators including:

  • Assignment Operators
  • Math Operators
  • Comparison Operators
  • Bitwise Operators



Contents


The Anatomy of a Ruby Operation

In Ruby, as with most other programming languages, 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 - Performs exponential (power) calculation on operators

Note that when performing division, if you do not want the result to be truncated to a round number, one of the operands in the operation must be epxressed as a float:

irb(main):001:0> 10 / 7
=> 1

In the above example sthe result as been rounded down to the nearest whole number. On the otehr hand, if we express one of the operands as a float, we get a more accurate answer:

irb(main):003:0> 10.0 / 7
=> 1.42857142857143

Ruby Assignment Operators

Earlier in this chapter we looked the basic assignment operator (=) which allows us to assign the result of an expression, for example y = 10.

The '=' assignment operator does not make any changes to the value before it is assigned to the variable. A number of assignment operators are available, however, that perform arithmetic on the value before assigning it to the variable. These are essentially combined arithmetic and assignment operators. The most common operators of this type, and their "long hand" equivalents are shown below:

Combined OperatorEquivalent
x += yx = x + y
x -= yx = x - y
x /= yx = x / y
x *= yx = x * y
x %= yx = x % y
x **= yx = x ** y

These combined operators provide a short way of assigning the results of arithmetic expressions between two variables or a variable and a value and having the result assigned to the first variable. For example:

x = 10
x += 5 # Assigns a value of 15 to variable x (the same as x = x + 5)

y = 20
y -= 10  # Assigns a value of 10 to variable y (the same as y = y - 10)

x = 10;
y = 5;

x /= y; # Assigns a value of 2 to variable x (the same as x = x / y)

Ruby Comparison Operators

Comparison operators are used to check for equality between two values. Ruby provides a number of such operators:

Comparison OperatorDescription
==Tests for equality. Returns true or false
.eql?Same as ==.
!=Tests for inequality. Returns true for inequality or false for equality
<Less than. Returns true if first operand is less than second operand. Otherwise returns false
>Greater than. Returns true if first operand is greater than second operand. Otherwise returns false.
>=Greater than or equal to. Returns true if first operand is greater than or equal to second operand. Otherwise returns false.
<=Less than or equal to. Returns true if first operand is less than or equal to second operand. Otherwise returns false.
<=>Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second.

Let's look at some of these operators in action:

irb(main):006:0> 1 == 1
=> true

irb(main):015:0> 1.eql? 2
=> false

irb(main):016:0> 10 < 1
=> false

irb(main):019:0> 10 <=> 10
=> 0

irb(main):020:0> 10 <=> 9
=> 1

irb(main):021:0> 10 <=> 11
=> -1

Ruby Bitwise Operators

Bitwise operators allow operations to be performed on number at the bit level. As you are probably already aware, computers deals solely with binary (in other words ones and zeros). For example, the computer sees the number 520 as 01010.

The Ruby bitwise operators allow us to operate and the level of the ones and zeros that make up a number:

Combined OperatorEquivalent
~Bitwise NOT (Complement)
|Bitwise OR
&Bitwise AND
^Bitwise Exclusive OR
<<Bitwise Shift Left
>>Bitwise Shift Right

As with the math operators, Ruby also provides a number of combined bitwise operators (for example ~=, >>=, <<= ^=, &=).

Operator Precedence

<captioRuby operators (high to low precedence)</caption>
Method Operator Description
Y [ ] [ ]= Element reference, element set
Y ** Exponentiation
Y ! ~ + - Not, complement, unary plus and minus (method names for the last two are +@ and -@)
Y * / % Multiply, divide, and modulo
Y + - Plus and minus
Y >> << Right and left shift
Y & Bitwise `and'
Y ^ | Bitwise exclusive `or' and regular `or'
Y <= < > >= Comparison operators
Y <=> == === != =~ !~ Equality and pattern match operators (!= and !~ may not be defined as methods)
&& Logical `and'
|| Logical `or'
.. ... Range (inclusive and exclusive)
? : Ternary if-then-else
= %= { /= -= += |= &= >>= <<= *= &&= ||= **= Assignment
defined? Check if symbol defined
not Logical negation
or and Logical composition
if unless while until Expression modifiers
begin/end Block expression