Project

General

Profile

Actions

Feature #8895

closed

Destructuring Assignment for Hash

Added by chendo (Jack Chen) about 9 years ago. Updated about 1 year ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:57131]

Description

Given Ruby already supports destructuring assignment with Array (a, b = [1, 2]), I propose destructuring assignments for Hash.

Basic example

  params = {name: "John Smith", age: 42}
  {name: name, age: age} = params

  # name == "John Smith"
  # age == 42

This would replace a common pattern of assigning hash values to local variables to work with.

General syntax

  { <key-expr> => <variable_name>,  } = <object that responds to #[]>

  # Symbols
  { foo: bar } = { foo: "bar" }
  bar == "bar"

  # Potential shorthand
  { foo } = { foo: "bar" }
  foo == "bar"

Use cases

  # MatchData
  { username: username, age: age } = "user:jsmith age:42".match(/user:(?<username>\w+) age:(?<age>\d+)/)
  username == "jsmith"
  age == "42"

Edge cases

  # Variable being assigned to more than once should use the last one
  { foo: var, bar: var } = {foo: 1, bar: 2}
  var == 2

Thoughts?


Related issues 2 (0 open2 closed)

Related to Ruby master - Bug #10028: nested rest keyword argumentRejectedmatz (Yukihiro Matsumoto)Actions
Is duplicate of Ruby master - Feature #6414: Destructuring Assignment ClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0