Ruby Assignment Operators
Assignment Operators
In Ruby assignment operator is done using the equal operator "=". This is applicable both for variables and objects, as strings, floats, and integers are actually objects in Ruby, you're always assigning objects.
Operator | Name | Description | Example |
---|---|---|---|
= | Equal operator "=" | Simple assignment operator, Assigns values from right side operands to left side operand | z = x + y will assign value of a + b into c |
+= | Add AND | Adds right operand to the left operand and assign the result to left operand | x += y is equivalent to x = x + y |
-= | Subtract AND | Subtracts right operand from the left operand and assign the result to left operand | x -= y is equivalent to x = x - y |
*= | Multiply AND | Multiplies right operand with the left operand and assign the result to left operand | x *= y is equivalent to x = x * y |
/= | Divide AND | Divides left operand with the right operand and assign the result to left operand | x /= y is equivalent to x = x / y |
%= | Modulus AND | Takes modulus using two operands and assign the result to left operand | x %= y is equivalent to x = x % y |
**= | Exponent AND | Performs exponential calculation on operators and assign value to the left operand | x **= y is equivalent to x = x ** y |
Example: Ruby assignment operator
puts ("assignment operator in Ruby")
x = 47
puts ("abbreviated assignment add")
puts x += 20
puts ("abbreviated assignment subtract")
puts x -= 20
puts ("abbreviated assignment multiply")
puts x *= 4
puts ("abbreviated assignment divide")
puts x /= 4
puts ("abbreviated assignment modulus")
puts x %= 6
puts ("abbreviated assignment exponent")
puts x **= 4
Output:
assignment operator in Ruby abbreviated assignment add 67 abbreviated assignment subtract 47 abbreviated assignment multiply 188 abbreviated assignment divide 47 abbreviated assignment modulus 5 abbreviated assignment exponent 625
Previous:
Ruby Comparison Operators
Next:
Ruby Parallel Assignment
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/ruby/ruby-assignment-operators.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics