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,
- Arithmetic Operators
- Comparison Operators
- Assignment Operators
- Logical Operators
- Range Operators
- Ternary Operator
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, and division.
| Operator | Meaning |
|---|---|
| + | 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.
| Operator | Meaning |
|---|---|
| == | 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.
| Operator | Meaning |
|---|---|
| = | 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.
| Operator | Meaning |
|---|---|
| && | 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.
| Operator | Meaning |
|---|---|
| .. | 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}"