[ruby-core:63711] [ruby-trunk - Feature #8895] Destructuring Assignment for Hash

From: ruby-core@...
Date: 2014-07-14 10:02:30 UTC
List: ruby-core #63711
Issue #8895 has been updated by Marc-Andre Lafortune.


Sean Linsley wrote:
> I don't follow. Can't this assignment behave the same way that method arg=
ument destructuring does?

I agree. Destructuring should work as method & block passing works (apart f=
rom block passing)

----------------------------------------
Feature #8895: Destructuring Assignment for Hash
https://bugs.ruby-lang.org/issues/8895#change-47761

* Author: Jack Chen
* Status: Open
* Priority: Normal
* Assignee:=20
* Category:=20
* Target version:=20
----------------------------------------

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

Basic example
-------------

```ruby
  params =3D {name: "John Smith", age: 42}
  {name: name, age: age} =3D params

  # name =3D=3D "John Smith"
  # age =3D=3D 42
```

This would replace a common pattern of assigning hash values to local varia=
bles to work with.

General syntax
--------------

```ruby
  { <key-expr> =3D> <variable_name>, =E2=80=A6 } =3D <object that responds =
to #[]>

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

  # Potential shorthand
  { foo } =3D { foo: "bar" }
  foo =3D=3D "bar"
```

Use cases
---------

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

Edge cases
----------

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

Thoughts?





--=20
https://bugs.ruby-lang.org/

In This Thread