Multiple assignment in Ruby
Unpacking arrays into variables, swaps, splats and nested pairs.
first, second = [10, 20]
puts first + second
first, second = second, first
puts "#{first}, #{second}"
head, *rest = [1, 2, 3, 4]
puts head
puts rest.inspect
# block parameters destructure pairs on their own
pairs = [["a", 1], ["b", 2]]
pairs.each { |letter, n| puts "#{letter}=#{n}" }
(low, high), label = [[1, 9], "range"]
puts "#{label}: #{low}-#{high}"
How it works
- Parallel assignment unpacks an array; swapping needs no temp.
head, *restsplits a list into its first element and the rest.- Block parameters destructure pairs without extra syntax.
- Parentheses reach into nested arrays during assignment.
Keywords and builtins used here
puts
The run, in numbers
- Lines
- 16
- Characters to type
- 359
- Tokens
- 123
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 92 seconds.
Step 2 of 3 in Nil & idioms, step 23 of 29 in Language basics.