How to Assign Several Variables at Once in Ruby
Ruby can fill several variables in one line: first, second = ['red', 'green'] puts each item of the array into its own variable. It's how Ruby code receives methods that return more than one value.
Syntax
<a>, <b> = <array>
<a>, <b> = <value>, <value>
| Part | What it does |
|---|---|
<a>, <b> = | The variables, separated by commas. |
<array> | Its items go into the variables in order. |
<value>, <value> | Several values on the right work the same way. |
The Ruby assignment documentation: "You can assign multiple values on the right-hand side to multiple variables". It also shows that multiple assignment can "swap two values in-place".
The Example
The example unpacks an array of two colors, then receives the two results of 17.divmod(5): the whole-number result and the remainder.
Prerequisites
- Ruby. This guide uses Ruby 4.0.10.
Step 1: Write the Code
Create a file named main.rb:

first, second = ['red', 'green']
puts first
puts second
quotient, remainder = 17.divmod(5)
puts "#{quotient} remainder #{remainder}"
17.divmod(5) returns the array [3, 2], which the second line unpacks.
Step 2: Run It
ruby main.rb
red
green
3 remainder 2

The command is the same in zsh, bash and PowerShell.
When the Counts Differ
Extra variables get nil: with a, b = 1, a was 1 and b was nil. Extra values are dropped. Neither case raises an error, so check the counts yourself.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| More variables than values | The extra variables are nil, silently | Match the counts |
| Naming a value you don't need | A variable that's never used | Name it _ or start it with _, as in payload, _header = ... |
| Swapping with a temporary variable | Extra lines | Write a, b = b, a |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A variable is unexpectedly nil | The right side had fewer values | Print the right side with p |
| Values land in the wrong variables | The order differs from the method's results | Check the order the method returns them in |
FAQ
How do I collect the rest into an array?
With a splat: first, *rest = [1, 2, 3] sets rest to [2, 3].
Can a method return several values?
Yes: return a, b returns them as an array, which the caller can unpack with multiple assignment.
Conclusion
a, b = array puts the array's items into separate variables in one line. Extra variables become nil, and _ marks a value you don't need.
Additional Resources
- Multiple assignment, in the Ruby documentation.
