typestar

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

  1. Parallel assignment unpacks an array; swapping needs no temp.
  2. head, *rest splits a list into its first element and the rest.
  3. Block parameters destructure pairs without extra syntax.
  4. Parentheses reach into nested arrays during assignment.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Nil & idioms, step 23 of 29 in Language basics.

← Previous Next →