Skip to content

Destructuring

a, b = [1, 2]
a, b = b, a # swap — RHS is evaluated before assignment

* captures zero or more remaining values into an array. At most one splat is allowed per pattern, and it can appear in any position:

first, *rest = [1, 2, 3, 4] # first = 1, rest = [2, 3, 4]
*init, last = [1, 2, 3, 4] # init = [1, 2, 3], last = 4
first, *middle, last = [1, 2, 3, 4] # first = 1, middle = [2, 3], last = 4

_ in a destructuring target position is a discard — it accepts a value but does not create a binding. Multiple _ in the same pattern are independent discards:

_, second, _ = [1, 2, 3] # only second is bound
first, _ = some_pair

_ is only ever a discard. It cannot be read, so using _ as an expression is a compile error.

Destructuring targets can carry type annotations:

a: Int, b: String = some_method
first: User, *rest: User = users
a, (b, c) = [1, [2, 3]] # a = 1, b = 2, c = 3
{ name:, age: } = user # binds name and age from a Hash or deconstructable object
{ name: n, age: a } = user # bind to different local names

var applies to all targets in a destructuring pattern, creating new bindings that shadow any existing variables:

var a, b = new_values # both a and b shadow any existing a, b

Any class can support destructuring by defining deconstruct (array-style) and/or deconstruct_keys (hash-style).

.NET’s Deconstruct convention uses out parameters, so deconstruct does not map to it directly. Instead, the compiler emits a Deconstruct shim alongside it, which lets C# deconstruct the object too. deconstruct_keys has no .NET counterpart and is only usable from Amethyst:

class Point
def initialize(@x: Int, @y: Int)
end
def deconstruct: Array[Int]
[@x, @y]
end
def deconstruct_keys(*keys: Symbol): Hash[Symbol, Int]
{ x: @x, y: @y }
end
end
point = Point.new(3, 7)
x, y = point # calls deconstruct — x = 3, y = 7
{ x:, y: } = point # calls deconstruct_keys
[[1, 2], [3, 4]].each do |(a, b)|
puts "#{a} and #{b}"
end
{ name: "Alice", role: :admin }.each do |(key, value)|
puts "#{key}: #{value}"
end

Tuple[T1, T2, ...] maps to .NET ValueTuple and supports destructuring natively:

pair: Tuple[String, Int] = ("Alice", 30)
name, age = pair