Assignments
An assignment expression specifies one or more values for one or more lvalues. lvalue is the term for something that can appear on the lefthand side of an assignment operator. (Values on the righthand side of an assignment operator are sometimes called rvalues by contrast.) Variables, constants, attributes, and array elements are lvalues in Ruby. The rules for and the meaning of assignment expressions are somewhat different for different kinds of lvalues, and each kind is described in detail in this section.
There are three different forms of assignment expressions in Ruby.
Simple assignment involves one lvalue, the = operator, and one rvalue. For
example:
x = 1 # Set the lvalue x to the value 1
Abbreviated assignment is a shorthand expression that updates the value of a
variable by applying some other operation (such as addition) to the
current value of the variable. Abbreviated assignment uses assignment
operators like += and *= that combine binary operators with an
equals sign:
x += 1 # Set the lvalue x to the value x + 1
Finally, parallel assignment is any assignment expression that has more than one lvalue or more than one rvalue. Here is a simple example:
x,y,z = 1,2,3 # Set x to 1, y to 2 and z to 3
Parallel assignment is more complicated when the number of lvalues is not the same as the number of rvalues or when there is an array on the right. Complete details follow.
The value of an assignment expression is the value (or an array of the values) assigned. Also, the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access