📚 Scripting Languages Tutorial

Scripting Languages

Learn scripting languages (Ruby, Perl, TCL and Tk) with simple explanations, examples, techniques and practical notes.

← Back to Scripting Languages

Operators in Ruby

An operator is a symbol used to perform an operation on values or variables.

For example,

a = 10
b = 5
puts a + b

In the above example, a and b are variables and + is an operator.

Ruby has different types of operators, those are,

  1. Arithmetic Operators
  2. Comparison Operators
  3. Assignment Operators
  4. Logical Operators
  5. Range Operators
  6. Ternary Operator

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, and division.

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Remainder
**Power

2. Comparison Operators

Comparison operators are used to compare two values. They give the result as either true or false.

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

3. Assignment Operators

Assignment operators are used to assign values to variables or update their values.

OperatorMeaning
=Assignment
+=Assignment after Addition
-=Assignment after Subtraction
*=Assignment after Multiplication
/=Assignment after Division
%=Assignment after Modulus

4. Logical Operators

Logical operators are used to combine two or more conditions.

OperatorMeaning
&&Logical AND – True when both conditions are true
||Logical OR – True when at least one condition is true
!Logical NOT – Changes true to false and false to true

5. Range Operators

Range operators are used to represent a group of values in a sequence.

Ruby provides two range operators.

OperatorMeaning
..Includes the last value
...Excludes the last value

6. Ternary Operator

The ternary operator is used as a short form of the if-else statement.

Syntax:
condition ? value1 : value2

In the above syntax, if the condition is true, value1 is selected, otherwise value2 is selected.

Example

Program: operatordemo.rb

# Arithmetic Operator
a = 10
b = 5
puts "Addition: #{a + b}"

# Comparison Operator
puts "Greater than: #{a > b}"

# Logical Operator
puts "Logical AND: #{a > 5 && b < 10}"

# Assignment Operator
a += 5
puts "Updated value of a: #{a}"

# Range Operator
puts "Range: #{(1..5).to_a.inspect}"

# Ternary Operator
result = a >= 15 ? "Pass" : "Fail"
puts "Result: #{result}"