Destructuring
Basic Multiple Assignment
Section titled “Basic Multiple Assignment”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 = 4first, *middle, last = [1, 2, 3, 4] # first = 1, middle = [2, 3], last = 4Discarding Values
Section titled “Discarding Values”_ 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 boundfirst, _ = some_pair_ is only ever a discard. It cannot be read, so using _ as an expression is a
compile error.
Type Annotations
Section titled “Type Annotations”Destructuring targets can carry type annotations:
a: Int, b: String = some_methodfirst: User, *rest: User = usersNested Destructuring
Section titled “Nested Destructuring”a, (b, c) = [1, [2, 3]] # a = 1, b = 2, c = 3Hash / Keyword Destructuring
Section titled “Hash / Keyword Destructuring”{ name:, age: } = user # binds name and age from a Hash or deconstructable object{ name: n, age: a } = user # bind to different local namesvar with Destructuring
Section titled “var with Destructuring”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, bCustom Deconstruct
Section titled “Custom Deconstruct”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 } endend
point = Point.new(3, 7)
x, y = point # calls deconstruct — x = 3, y = 7{ x:, y: } = point # calls deconstruct_keysBlock Parameter Destructuring
Section titled “Block Parameter Destructuring”[[1, 2], [3, 4]].each do |(a, b)| puts "#{a} and #{b}"end
{ name: "Alice", role: :admin }.each do |(key, value)| puts "#{key}: #{value}"endTuple Types
Section titled “Tuple Types”Tuple[T1, T2, ...] maps to .NET ValueTuple and supports destructuring natively:
pair: Tuple[String, Int] = ("Alice", 30)name, age = pair