[ruby-core:76799] [Ruby trunk Feature#8895] Destructuring Assignment for Hash
From:
alxtskrnk@...
Date:
2016-08-09 17:42:59 UTC
List:
ruby-core #76799
Issue #8895 has been updated by bug hit.
the closest you can get to hash destructuring is via block params:
~~~ ruby
{a: 1, b: 2}.tap do |a:, b:|
end
~~~
but unfortunately this has its own issues (#11048), it's too strict about missing/extra keys, which doesn't make sense since blocks are intended to be looser with parameter binding.
----------------------------------------
Feature #8895: Destructuring Assignment for Hash
https://bugs.ruby-lang.org/issues/8895#change-60022
* Author: Jack Chen
* Status: Open
* Priority: Normal
* Assignee:
----------------------------------------
Given Ruby already supports destructuring assignment with Array (a, b = [1, 2]), I propose destructuring assignments for Hash.
Basic example
-------------
```ruby
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
--------------
```ruby
{ <key-expr> => <variable_name>, … } = <object that responds to #[]>
# Symbols
{ foo: bar } = { foo: "bar" }
bar == "bar"
# Potential shorthand
{ foo } = { foo: "bar" }
foo == "bar"
```
Use cases
---------
```ruby
# MatchData
{ username: username, age: age } = "user:jsmith age:42".match(/user:(?<username>\w+) age:(?<age>\d+)/)
username == "jsmith"
age == "42"
```
Edge cases
----------
```ruby
# Variable being assigned to more than once should use the last one
{ foo: var, bar: var } = {foo: 1, bar: 2}
var == 2
```
Thoughts?
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>