Ruby - Assignment operators

1. Introduction

In Ruby, assignment operators are used to assign values to variables. The most common assignment operator is =, but Ruby also supports compound assignment operators that combine arithmetic or bitwise operations with assignment.

2. Program Steps

1. Initialize a variable.

2. Use various assignment operators to modify the variable's value.

3. Print the results.

3. Code Program

# Simple assignment
x = 10
puts "Initial value of x: #{x}"
# Add and assign
x += 5
puts "After adding 5: #{x}"
# Subtract and assign
x -= 3
puts "After subtracting 3: #{x}"
# Multiply and assign
x *= 2
puts "After multiplying by 2: #{x}"
# Divide and assign
x /= 3
puts "After dividing by 3: #{x}"
# Modulus and assign
x %= 4
puts "After taking modulus 4: #{x}"
# Exponent and assign
x **= 2
puts "After raising to the power of 2: #{x}"

Output:

Initial value of x: 10
After adding 5: 15
After subtracting 3: 12
After multiplying by 2: 24
After dividing by 3: 8
After taking modulus 4: 0
After raising to the power of 2: 0

Explanation:

1. The = operator is the simple assignment operator, it assigns the value on its right to the variable on its left.

2. The += operator adds the value on its right to the variable on its left and then assigns the result to the variable.

3. The -= operator subtracts the value on its right from the variable on its left and assigns the result.

4. The *= operator multiplies the variable by the value on its right and then assigns the result.

5. The /= operator divides the variable by the value on its right and assigns the result.

6. The %= operator takes the modulus of the variable with the value on its right and assigns the result.

7. The = operator raises the variable to the power of the value on its right and assigns the result.


Comments