Ruby | Operators

An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows:

Arithmetic Operators

These are used to perform arithmetic/mathematical operations on operands.



  • Addition(+): operator adds two operands. For example, x+y.
  • Subtraction(-): operator subtracts two operands. For example, x-y.
  • Multiplication(*): operator multiplies two operands. For example, x*y.
  • Division(/): operator divides the first operand by the second. For example, x/y.
  • Modulus(%): operator returns the remainder when first operand is divided by the second. For example, x%y.
  • Exponent(**): operator returns exponential(power) of the operands. For example, x**y.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Airthmetic Operators
  
# Addition
puts ("Addition:")
puts (10 + 20)
  
# Subtraction
puts ("Subtraction:")
puts (40 - 20)
  
# Division
puts ("Division:")
puts (100 / 20)
  
# Multiplication
puts ("Multiplication:")
puts (10 * 20)
  
# Modulus
puts ("Modulus:")
puts (20 % 7)
  
# Exponent
puts ("Exponent:")
puts (2 ** 4)

chevron_right


Output:

Addition:
30
Subtraction:
20
Division:
5
Multiplication:
200
Modulus:
6
Exponent:
16

Comparison Operators

Comparison operators or Relational operators are used for comparison of two values. Let’s see them one by one:

  • Equal To(==) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true.
  • Not Equal To(!=) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
  • Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
  • Less than(<) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
  • Greater Than Equal To(>=) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
  • Less Than Equal To(<=) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.
  • Combined combination (<=>) operator return 0 when first operand equal to second, return 1 when first operand is greater than second operand, and return -1 when first operator is less than second operand.
  • Case Equality Operator(===) It will test equality in case statement.
  • ‘.eql?’ This operator returns true if the receiver and argument have both the same type and equal values.
  • ‘Equal?’ This operator Returns true if if the receiver and argument have the same object id.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Comparision Operators
   
puts "Equal To Operator:"
puts (10 == 20)
   
puts "Not Equal To Operator:"
puts (40 != 20)
   
puts "Greater than Operator"
puts (100 > 20)
   
puts "Less than Operator"
puts (10  < 20)
   
puts "Less than Equal To Operator"
puts (2  <=  5)
  
puts "Greater than Equal To Operator"
puts (2  >=  5)
   
puts "Combined combination operator"
puts(20 <=> 20)
puts(10 <=> 20)
puts(20 <=> 10)

chevron_right


Output:

Equal To Operator:
false
Not Equal To Operator:
true
Greater than Operator
true
Less than Operator
true
Less than Equal To Operator
true
Greater than Equal To Operator
false
Combined combination operator
0
-1
1

Logical Operators

They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:

  • Logical AND(&&) operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. Using “and” is an alternate for && operator. For example, a && b returns true when both a and b are true (i.e. non-zero).
  • Logical OR(||) operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. Using “or” is an alternate for || operator. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
  • Logical NOT(!): operator returns true the condition in consideration is not satisfied. Otherwise it returns false. Using “not” is an alternate for ! operator. For example, !true returns false.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Logical Operators
   
# Variables
a = 10
b = 20
c = 30
  
# using && operator
if a == 10 && b == 20 && c == 30
    puts "Logical AND Operator"
    puts result = a * b * c
end
  
# using || operator
puts "Logical OR operator"
if a == 10 || b == 20
    puts result = a + b + c
end
  
# using ! operator
puts "Logical Not Operator"
puts !(true)
     

chevron_right


Output:


Logical AND Operator
6000
Logical OR operator
60
Logical Not Operator
false

Assignment Operators

Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:

  • Simple Assignment (=): operator is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
  • Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left.
  • Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left.
  • Multiply AND Assignment (*=) operator is used for multiplying left operand with right operand and then assigning it to variable on the left.
  • Divide AND Assignment (/=) operator is used for dividing left operand with right operand and then assigning it to variable on the left.
  • Modulus AND Assignment (%=) operator is used for assigning modulo of left operand with right operand and then assigning it to variable on the left.
  • Exponent AND Assignment (**=) operator is used for raising power of left operand to right operand and assigning it to variable on the left.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Assignments Operators
   
puts "Simple assignment operator"
puts a = 20
  
puts "Add AND assignment operator"
puts a += 10
  
puts "Subtract AND assignment operator"
puts a -= 5
  
puts "Multiply AND assignment operator"
puts a *= 10
  
puts "Divide AND assignment operator"
puts a /= 4
  
puts "Modulus AND assignment operator"
puts a %= 3
  
puts "Exponent AND assignment operator"
puts a **= 3

chevron_right


Output:

Simple assignment operator
20
Add AND assignment operator
30
Subtract AND assignment operator
25
Multiply AND assignment operator
250
Divide AND assignment operator
62
Modulus AND assignment operator
2
Exponent AND assignment operator
8

Bitwise Operators

In Ruby, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators :

  • Bitwise AND (&) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
  • Bitwise OR (|) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
  • Bitwise XOR (^) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
  • Left Shift (<<) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
  • Right Shift (>>) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
  • Ones Complement (~) This operator takes a single number and used to perform complement operation of 8-bit.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Bitwise Operators
  
# variables
a = 10
b = 20
  
puts "Bitwise AND operator"
puts (a & b)
  
puts "Bitwise OR operator"
puts (a |b)
  
puts "Bitwise XOR operator"
puts (a ^ b)
  
puts "Bitwise Complement operator"
puts (~a)
  
puts "Binary right shift operator"
puts (a >> 2)
  
puts "Binary left shift operator"
puts (a << 2)

chevron_right


Output:

Bitwise AND operator
0
Bitwise OR operator
30
Bitwise XOR operator
30
Bitwise Complement operator
-11
Binary right shift operator
2
Binary left shift operator
40

Ternary Operator

It is a conditional operator which is a shorthand version of the if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression.


Syntax :

condition ? first_expression : second_expression;

Explanation :

condition: It be evaluatedluate to true or false.

If the condition is true
 first_expression is evaluated and becomes the result. 

If the condition is false, 
 second_expression is evaluated and becomes the result. 

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Ternary Operator
  
# variable
marks_obtained = 100
  
# using ternary operator
result = marks_obtained > 40 ? 'Pass' : 'Fail'
  
# displaying output
puts result

chevron_right


Output:

Pass

Range Operators

In Ruby, range operators are used for creating the specified sequence range of specified elements. There are two range operators in Ruby as follows:

  • Double Dot (..) operator is used to create a specified sequence range in which both the starting and ending element will be inclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9, 10.
  • Triple Dot (…) operator is used to create a specified sequence range in which only starting element will be inclusive and ending element will be exclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the Range Operator
  
# Array value separator
$, =", "  
  
# using .. Operator
range_op = (7 .. 10).to_a
  
# displaying result
puts "#{range_op}"
  
# using ... Operator
range_op1 = (7 ... 10).to_a
  
# displaying result
puts "#{range_op1}"

chevron_right


Output:

[7, 8, 9, 10]
[7, 8, 9]

defined? Operator

The defined? the operator is a special operator which is used to check whether the passed expression is defined or not. It returns nil if passed argument is not defined, otherwise, it returns a string of that argument which defines that.


Syntax:

defined? expression_to_be_checked 

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# the defined? Operator
  
# varibles
GFG 1
Geeks = 70
  
  
puts ("define? Operator Results")
  
# using defined? Operator
# it returns constant
puts defined? GFG        
  
# it returns constant
puts defined? Geeks 
  
# it returns expression
puts defined? a  
         
# it returns expression
puts defined? 50   

chevron_right


Output:

define? Operator Results
constant
constant

expression

Dot “.” and Double Colon “::” Operators

  • Dot (.) operator is used to access the methods of a class.
  • Double Colon (::) operator is used to access the constants, class methods, and instance methods defined within a class or module to anywhere outside the class or module. The important point to remember is that classes and methods may be considered constants in Ruby and also prefix the :: Const_name with the expression which returns the appropriate class object. If no prefix expression is used then by default the main Object class is used.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate 
# Dot “.” and Double Colon 
# “::” Operators
  
# defined constant on main Object class
CONS = 5   
  
# define module
module Geeks
      
   CONS = 5
     
   # set global CONS to 7
   ::CONS = 7   
     
    # set local CONS to 10
   CONS = 10    
end
  
# displaying global CONS value
puts CONS     
  
# displaying local "Geeks" CONS value
# using :: operator
puts Geeks::CONS   
  
class Gfg
    def Geeks2
        puts "Dot Operator"
    end
end
  
# calling Geeks2 module using 
# Dot(.) operator
puts Gfg.new.Geeks2

chevron_right


Output:

7
10
Dot Operator

main.rb:14: warning: already initialized constant CONS
main.rb:6: warning: previous definition of CONS was here
main.rb:17: warning: already initialized constant Geeks::CONS
main.rb:11: warning: previous definition of CONS was here


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.