Ruby Operators

Follow Techotopia on Twitter Bookmark and Share

From Techotopia

Jump to: navigation, search
PreviousTable of ContentsNext
Advanced Ruby ArraysRuby Operator Precedence


Purchase and download the PDF and ePub versions of this Ruby eBook for only $8.99  Add to Cart


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



[edit] 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 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

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

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

[edit] 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 expressed as a float:

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

In the above example the result has been rounded down to the nearest whole number. On the other 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

[edit] 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)

[edit] Parallel Assignment

Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example:

a = 10
b = 20
c = 30

The above code may be more quickly declared using parallel assignment:

a, b, c = 10, 20, 30

Parallel assignment is also useful for swapping the values held in two variables:

a, b = b, c

[edit] 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

[edit] Ruby Bitwise Operators

Bitwise operators allow operations to be performed on number at the bit level. As you are probably already aware, computers deal 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 at 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 ~=, >>=, <<= ^=, &=).

[edit] Summary

In this chapter of Ruby Essentials we have covered the basics of Ruby operators, expressions and assignments. In the next chapter we will look at the all important area of Ruby Operator Precedence.


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99

Add to Cart



PreviousTable of ContentsNext
Advanced Ruby ArraysRuby Operator Precedence
Views
Personal tools

Find us on Facebook