Introduction

In this blog, we will see what is assignments and abbreviated assignments and then we will learn about abbreviated assignments using different pseudo-operators with code implementation.
An abbreviated assignment is a shorthand expression that updates the value of a variable by performing other operations (such as addition) on the variable's current value. It is used to express something more concisely.
So, now let us learn about Abbreviated Assignment in detail.
Abbreviated Assignment
The equal operator "=" is used in Ruby as an assignment operator. This applies to variables and objects because strings, floats, and integers are all objects in Ruby, and we're always assigning objects. A combination of an assignment and another operation is an abbreviated assignment. It's most commonly used to increase the value of a variable: x += 9.
+= isn't an actual Ruby operator(it is a pseudo-operator), and the expression above is just a shorthand for x = x + 9.
An abbreviated assignment works when there is a single lvalue on the left and a single value on the right. When the lvalue is a constant, it should not be used since it will reassign the constant, resulting in a warning. When the lvalue is an attribute, the abbreviated assignment can be used.
Note -
- An lvalue is something present on the left-hand side of an assignment operator
- Values on the right-hand side of an assignment operator are commonly referred to as rvalues
Abbreviated Assignment pseudo-operators
Assignment |
Expansion |
x += y |
x = x + y |
x -= y |
x = x - y |
x *= y |
x = x * y |
x /= y |
x = x / y |
x %= y |
x = x % y |
x **= y |
x = x ** y |
x &&= y |
x = x && y |
x ||= y |
x = x || y |
x &= y |
x = x & y |
x |= y |
x = x | y |
x ^= y |
x = x ^ y |
x <<= y |
x = x << y |
x >>= y |
x = x >> y |
Pseudo-Operators are not true operators themselves; they are simply shorthand for expressions that use other operators.