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 assignmentx = 10puts "Initial value of x: #{x}"# Add and assignx += 5puts "After adding 5: #{x}"# Subtract and assignx -= 3puts "After subtracting 3: #{x}"# Multiply and assignx *= 2puts "After multiplying by 2: #{x}"# Divide and assignx /= 3puts "After dividing by 3: #{x}"# Modulus and assignx %= 4puts "After taking modulus 4: #{x}"# Exponent and assignx **= 2puts "After raising to the power of 2: #{x}"Output:
Initial value of x: 10After adding 5: 15After subtracting 3: 12After multiplying by 2: 24After dividing by 3: 8After taking modulus 4: 0After 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
Post a Comment