Skip to main content

How to Assign Several Variables at Once in Ruby

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<a>, <b> = <array>
<a>, <b> = <value>, <value>
PartWhat 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:

main.rb, which assigns first and second from an array of red and green and puts both, then assigns quotient and remainder from 17.divmod(5) and puts them in a sentence.

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​

Terminal
ruby main.rb
Output
red
green
3 remainder 2

A zsh terminal where ruby main.rb prints red, green and 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​

MistakeWhat happensDo this instead
More variables than valuesThe extra variables are nil, silentlyMatch the counts
Naming a value you don't needA variable that's never usedName it _ or start it with _, as in payload, _header = ...
Swapping with a temporary variableExtra linesWrite a, b = b, a

Troubleshooting​

SymptomLikely causeFix
A variable is unexpectedly nilThe right side had fewer valuesPrint the right side with p
Values land in the wrong variablesThe order differs from the method's resultsCheck 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​