Introduction
Assignment in ruby stands for assigning values from right side operands to left side operands. In Ruby, there are various types of assignments possible. All possible assignments are listed below.
- Assigning to Variables
- Assigning to Constants
- Assigning to Attributes and Array Elements
- Abbreviated Assignment
- Parallel Assignment
In this blog, we will discuss the concept of assignment and assigning to constants in Ruby. So, first, let’s get started with the introduction of an assignment expression.
Assignment Expression
A value for one or more lvalues is specified by an assignment expression. The term lvalue refers to something that can appear on the left side of an assignment operator. (Values on the righthand side of an assignment operator are frequently referred to as rvalues.)
In Ruby, lvalues are variables, constants, attributes, and array elements. The criteria and meaning of assignment expressions vary slightly for different types of lvalues, which are detailed in detail in this section.
In Ruby, assignment expressions can have three different forms.
-
Simple assignment: Simple assignment involves one lvalue, the = operator, and one rvalue. For example;
x = 13 # Set the lvalue x to the value 13
-
Abbreviated assignment: An abbreviated assignment is a shorthand expression that updates the value of a variable by performing another operation (such as addition) on the variable's current value. Assignment operators like += and *=, which combine binary operators with an equal sign, are used in the abbreviated assignments. For example;
x += 2 # Set the lvalue x to the value x + 2
-
Parallel assignment: Any assignment expression with more than one lvalue or more than one rvalue is considered a parallel assignment. For example;
x,y,z = 2,3,4 # Set x to 2, y to 3 and z to 4