Ruby operators perform arithmetic, compare values, test conditions, and assign results.
A simple example
Test two conditions
Start withn is 2
Do thisGreater than 0 and less than 3?
Resultyes
Both comparisons succeed, so the program prints yes.lesson.rb
n = 2
puts "yes" if n > 0 && n < 3
Output
yes
Look up a shelf safely
A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.
Types of Operators
Arithmetic operator
Relational operator
Logical operator
Bitwise operator
Assignment operator
Range operator
Dot and Colon operator
Defined operator
Ternary operator
Ruby Arithmetic Operator
Ruby provides arithmetic operators for addition, subtraction, multiplication, division, remainder, and exponentiation.
Name
Operator
Description
Addition
+
Adds the operands.
subtraction
-
Subtracts the right operand from the left.
Multiplication
*
Multiplies the operands.
Division
/
Divides the left operand by the right.
Modulo (or) Modulus
%
Computes the modulo. For integers, the result has the sign of the divisor unless it is zero.
Example: #1 - Arithmetic operator
Apply each arithmetic operator to a and b.
Ruby source code
x = 5
y = 3
puts("The value of (x + y) is " + (x + y).to_s)
puts("The value of (x - y) is " + (x - y).to_s)
puts("The value of (x * y) is " + (x * y).to_s)
puts("The value of (x / y) is " + (x / y).to_s)
puts("The value of (x % y) is " + (x % y).to_s)
Output
The value of (x + y) is 8
The value of (x - y) is 2
The value of (x * y) is 15
The value of (x / y) is 1
The value of (x % y) is 2
Advertisements
Example: #2 - Arithmetic operator division
Compare division with Integer and Float operands.
Ruby source code
i = 5
j = 2
k = 2.0
# By default, the data type of the result is int (i.e. 2)
puts("The value of (i / j) is " + (i / j).to_s)
# By default, the data type of the result is float (i.e. 2.5)
puts("The value of (i / k) is " + (i / k).to_s)
# Cast the divident of type float (i.e. j)
# So the result is 2.5
puts("The value of (i / j.to_f) is " + (i / j.to_f).to_s)
Output
The value of (i / j) is 2
The value of (i / k) is 2.5
The value of (i / j.to_f) is 2.5
Ruby Relational Operator
Relational operators compare values. For example, a < b tests their order and a == b tests equality.
Name
Operator
Description
Equal to
==
Compares two values and returns true only if both are equal.
Not Equal to
!=
Compares two values and returns true only if both are not equal.
Less than
<
Compares two values and returns true only if the left operand is less than the right operand.
Greater than
>
Compares two values and returns true only if the left operand is greater than the right operand.
Less than or equal to
<=
Compares two values and returns true only if the left operand is less than or equal to the right operand.
Greater than or equal to
>=
Compares two values and returns true only if the left operand is greater than or equal to the right operand.
Example: #3 - Relational Operator
Compare the operands for equality and order.
Ruby source code
name = "John"
age = 24
# String Comparision
result = name == "John" # true
puts("Check the name is John : " + result.to_s)
# Numeric Comparision
result = age == 24 # true
puts("Check the person age is 24 : " + result.to_s)
result = age != 20 # true
puts("Check the person age is not equal to 20 : " + result.to_s)
result = age < 18 # false
puts("Check the person is minor (i.e. less than 18) : " + result.to_s)
result = age > 58 # false
puts("Check the person is senior citizen (i.e. greater than 58) : " + result.to_s)
result = age <= 18 # false
puts("Check the person age is less than or equal to 18 : " + result.to_s)
result = age >= 24 # true
puts("Check the person age is greater than or equal to 24 : " + result.to_s)
Output
Check the name is John : true
Check the person age is 24 : true
Check the person age is not equal to 20 : true
Check the person is minor (i.e. less than 18) : false
Check the person is senior citizen (i.e. greater than 58) : false
Check the person age is less than or equal to 18 : false
Check the person age is greater than or equal to 24 : true
Ruby Logical Operator
The && and || operators short-circuit and return an operand. Only false and nil are falsey in Ruby. Use ! to negate a condition.
Name
Operator
Description
Logical AND
&&
Compares two expressions and returns true only if both evaluate to true.
Logical OR
||
Compares two expressions and returns true either one evaluate to true.
Logical NOT
!
Negates the logical value.
Example: #4 - Logical Operator
Compare the results of AND, OR, and NOT.
Ruby source code
john = 32
peter = 19
# Logical AND operation
result1 = (john > 18) && (peter > 18);
result2 = (john < 18) && (peter < 18);
puts("Both are above 18 years (Logical AND) : " + result1.to_s);
puts("Both are below 18 years (Logical AND) : " + result2.to_s);
# Logical OR operation
result3 = (john > 18) || (peter > 18);
result4 = (john > 30) || (peter > 30);
result5 = (john > 50) || (peter > 50);
puts("Anyone is above 18 years (Logical OR) : " + result3.to_s);
puts("Anyone is above 30 years (Logical OR) : " + result4.to_s);
puts("Anyone is above 50 years (Logical OR) : " + result5.to_s);
# Logical NOT operation
result6 = !(john > 18);
puts("Check the john's age is below 18 years : " + result6.to_s);
Output
Both are above 18 years (Logical AND) : true
Both are below 18 years (Logical AND) : false
Anyone is above 18 years (Logical OR) : true
Anyone is above 30 years (Logical OR) : true
Anyone is above 50 years (Logical OR) : false
Check the john's age is below 18 years : false
Ruby Bitwise Operator
Ruby's integer bitwise operators act on bit patterns. Use << and >> to shift bits.
Name
Operator
Description
Left Shift
<<
Converts the numerical representation to the equivalent binary representation and shifts a 0 into the rightmost n position
Signed Right Shift
>>
Converts the numerical representation to the equivalent binary representation and shifts 1 only if the number is negative otherwise 0 into the leftmost n position
Unsigned Right Shift
Converts the numerical representation to the equivalent binary representation and shifts a 0 into the leftmost n position. In Ruby there is no operator available for Unsigned Right Shift but we can achieve in another way.
Bitwise AND
&
Sets a bit when both input bits are set.
Bitwise OR
|
Sets a bit when either input bit is set.
Bitwise XOR
^
Sets a bit when the corresponding input bits differ.
Bitwise Complement
~
Flips each bit of the operand.
Example: #5 - Bitwise Shift Operator
Compare left shift, signed right shift, and unsigned right shift.
Ruby source code
x = -6
y = 6
result = 0
# Left Shift
# Remove the leftmost two binary digits
# and place the binary b'0' to the rightmost 2 position
# to make it 32 bit in length
# x => 11111111 11111111 11111111 11111010 => -6
# x << 2 => 11111111 11111111 11111111 11101000 => -24
# y => 00000000 00000000 00000000 00000110 => 6
# y << 2 => 00000000 00000000 00000000 00011000 => 24
result = x << 2;
puts("Left Shift (x << 2) is : " + result.to_s);
result = y << 2;
puts("Left Shift (y << 2) is : " + result.to_s);
# Signed Right Shift - Negative Number
# Remove the rightmost two binary digits
# and place the binary b'1' to the leftmost 2 position
# to make it 32 bit in length
# x => 11111111 11111111 11111111 11111010 => -6
# x >> 2 => 11111111 11111111 11111111 11111110 => -2
# Signed Right Shift - Positive Number
# Remove the rightmost two binary digits
# and place the binary b'0' to the leftmost 2 position
# to make it 32 bit in length
# y => 00000000 00000000 00000000 00000110 => 6
# y >> 2 => 00000000 00000000 00000000 00000001 => 1
result = x >> 2;
puts("Signed Right Shift (x >> 2) is : " + result.to_s);
result = y >> 2;
puts("Signed Right Shift (y >> 2) is : " + result.to_s);
# Unsigned Right Shift
# Remove the rightmost two binary digits
# and place the binary b'0' to the leftmost 2 position
# to make it 32 bit in length
# x => 11111111 11111111 11111111 11111010 => -6
# x >>> 2 => 00111111 11111111 11111111 11111110 => 1073741822
# y => 00000000 00000000 00000000 00000110 => 6
# y >>> 2 => 00000000 00000000 00000000 00000001 => 1
mask = (1 << (32 - 2)) - 1
result = (x >> 2) & mask
puts("Unsigned Right Shift (x >>> 2) is : " + result.to_s)
mask = (1 << (32 - 2)) - 1
result = (y >> 2) & mask
puts("Unsigned Right Shift (y >>> 2) is : " + result.to_s)
Output
Left Shift (x << 2) is : -24
Left Shift (y << 2) is : 24
Signed Right Shift (x >> 2) is : -2
Signed Right Shift (y >> 2) is : 1
Unsigned Right Shift (x >>> 2) is : 1073741822
Unsigned Right Shift (y >>> 2) is : 1
Example: #6 - Bitwise Operator
Compare bitwise AND, OR, XOR, and complement.
Ruby source code
x = 6
y = 3
result = 0
# Bitwise AND
# x => 00000000 00000000 00000000 00000110 => 6
# y => 00000000 00000000 00000000 00000011 => 3
# x & y => 00000000 00000000 00000000 00000010 => 2
result = x & y;
puts("Bitwise AND (x & y) is : " + result.to_s);
# Bitwise OR
# x => 00000000 00000000 00000000 00000110 => 6
# y => 00000000 00000000 00000000 00000011 => 3
# x | y => 00000000 00000000 00000000 00000111 => 7
result = x | y;
puts("Bitwise OR (x | y) is : " + result.to_s);
# Bitwise XOR
# x => 00000000 00000000 00000000 00000110 => 6
# y => 00000000 00000000 00000000 00000011 => 3
# x ^ y => 00000000 00000000 00000000 00000101 => 5
result = x ^ y;
puts("Bitwise XOR (x ^ y) is : " + result.to_s);
# Bitwise Complement
# x => 00000000 00000000 00000000 00000110 => 6
# ~x => 11111111 11111111 11111111 11111001 => -7
result = ~x;
puts("Bitwise Complement ~x is : " + result.to_s);
Output
Bitwise AND (x & y) is : 2
Bitwise OR (x | y) is : 7
Bitwise XOR (x ^ y) is : 5
Bitwise Complement ~x is : -7
Advertisements
Ruby Assignment Operator
Assignment stores a value. A compound assignment such as x += 1 updates a variable using its previous value.
Name
Operator
Description
Simple Assignment
=
Assigns a value to a variable.
Increment Assignment
+=
Adds a value and the variable and assigns the result to that variable.
Decrement Assignment
-=
Subtracts a value and the variable and assigns the result to that variable.
Multiplication Assignment
*=
Multiplies a value and the variable and assigns the result to that variable.
Division Assignment
/=
Divides a value and the variable and assigns the result to that variable.
Modulo Assignment / Modulus assignment
%=
Modulo a value and the variable and assigns the result to that variable.
Bitwise Left shift assignment
<<=
Performs a Bitwise Left shift operation between a variable and a value, finally assigns the result to that variable.
Bitwise signed right shift assignment
>>=
Performs a Bitwise Signed right shift operation between a variable and a value, finally assigns the result to that variable.
Bitwise AND assignment
&=
Performs a Bitwise AND operation between a variable and a value, finally assigns the result to that variable.
Bitwise OR assignment
|=
Performs a Bitwise OR operation between a variable and a value, finally assigns the result to that variable.
Bitwise XOR assignment
^=
Performs a Bitwise XOR operation between a variable and a value, finally assigns the result to that variable.
Example: #7 - Arithmetic Assignment operator
Trace x and y through the arithmetic assignments.
Ruby source code
x = 6
y = 1
y += x; # 6 + 1 = 7
puts("The value of y => (y += x) is " + y.to_s);
y = 10;
y -= x; # 10 - 6 = 4
puts("The value of y => (y -= x) is " + y.to_s);
y = 2;
y *= x; # 6 * 2 = 12
puts("The value of y => (y *= x) is " + y.to_s);
y = 18;
y /= x; # 18 / 6 = 3
puts("The value of y => (y /= x) is " + y.to_s);
y = 20;
y %= x; # 20 % 6 = 2
puts("The value of y => (y %= x) is " + y.to_s);
Output
The value of y => (y += x) is 7
The value of y => (y -= x) is 4
The value of y => (y *= x) is 12
The value of y => (y /= x) is 3
The value of y => (y %= x) is 2
Example: #8 - Bitwise Assignment operator
Trace x and y through the bitwise assignments.
Ruby source code
x = 2
y = 6
y <<= x; # 6 << 2 = 24
puts("The value of y => (y <<= x) is " + y.to_s)
x = 2
y = 6
y >>= x # 6 >> 2 = 1
puts("The value of y => (y >>= x) is " + y.to_s)
x = 3
y = 6
y &= x # 6 & 3 = 2
puts("The value of y => (y & x) is " + y.to_s)
x = 3
y = 6
y |= x # 6 | 3 = 7
puts("The value of y => (y | x) is " + y.to_s)
x = 3
y = 6
y ^= x # 6 ^ 3 = 5
puts("The value of y => (y ^ x) is " + y.to_s)
Output
The value of y (y <<= x) is 24
The value of y (y >>= x) is 1
The value of y (y &= x) is 2
The value of y (y |= x) is 7
The value of y (y ^= x) is 5
Ruby Range Operator
A Ruby range includes its starting value. Two dots include the end, and three dots exclude it.
Name
Operator
Description
Double Dot
..
Includes both endpoints. The integer range 6..9 contains 6, 7, 8, and 9.
Triple Dot
...
Excludes the ending value. The integer range 6...9 contains 6, 7, and 8.
Example: #9 - Range Operator
Compare the values produced by inclusive and exclusive integer ranges.
Ruby source code
print("Generate a sequence for 6..9 => ")
seq = 6..9
for i in seq do
print(i.to_s + " ")
end
print("\nGenerate a sequence for 6...9 => ")
seq = 6...9
for i in seq do
print(i.to_s + " ")
end
Output
Generate a sequence for 6..9 => 6 7 8 9
Generate a sequence for 6...9 => 6 7 8
Ruby method calls and constant lookup
Use a dot to call a method on a receiver. Use a double colon to look up a constant in a module or class.
Calling a method and reading a constant
The first line calls the upcase method on a string. The second reads the SEPARATOR constant from File.