In Ruby, multiple assignments can be done in a single operation. Multiple assignments contain an expression that has more than one lvalue, more than one rvalue, or both. The order of the values assigned to the right side of = operator must be the same as the variables on the left side. The assignments are effectively performed in parallel, so the values assigned are not affected by the assignment itself.
lvalue1,... = rvalue2, ...
Parameters: left side variables are called lvalues and right side variables are called rvalues.
- If an assignment has one lvalue and more than one rvalue, then Ruby creates an array to hold the rvalues and assigns that array to the lvalue.
- If an assignment has more lvalues than rvalues, then the excess lvalues are set to nil.
- If an assignment has more lvalues and a single array rvalue, then each array value is assigned to a single lvalue from left to right.
- If the last lvalue is preceded by an asterisk(* also called splat operator), all the remaining rvalues will be collected and assigned to that lvalue as an array.
- Similarly, if the last rvalue is an array, you can prefix it with an asterisk, which effectively expands it into its constituent values in place. (This is not necessary if the rvalue is the only thing on the right-hand side, the array will be expanded automatically.)
Result 1: 2 3 4 Result 2: 9 3 5
One lvalue and multiple rvalue: 2 3 4 Three lvalues and two rvalues: 2 3 NilClass
Result 1: 2 3 4 Result 2: 1
2 4 6
- Ruby For Beginners
- Ruby | Keywords
- Ruby | Loops (for, while, do..while, until)
- Ruby Programming Language (Introduction)
- Ruby | Data Types
- Ruby | Types of Variables
- Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
- Ruby | Class & Object
- Ruby | Operators
- Ruby | String Basics
- Ruby | Arrays
- Ruby | Blocks
- Ruby | Control Flow Alteration
- Ruby | Ranges
- Ruby | Pre-define Variables & Constants
- Ruby | unless Statement and unless Modifier
- Ruby | Case Statement
- Similarities and Differences between Ruby and C language
- Similarities and Differences between Ruby and C++
- Hello World in Ruby
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.