From: ko1@... Date: 2014-07-10T07:11:36+00:00 Subject: [ruby-core:63622] [ruby-trunk - Feature #8895] Destructuring Assignment for Hash Issue #8895 has been updated by Koichi Sasada. +1 for this proposal. I feel it is fine for me: ```ruby k1: 1, k2: 2 = h kr1:, kr2: = h #=> same as k1 = h.fetch(:k1, 1) k2 = h.fetch(:k2, 2) kr1 = h.fetch(:k1) kr2 = h.fetch(:k2) # mixed k1: 1, k2: 2, kr1:, kr2: = h # compile to k1 = h.fetch(:k1, 1) k2 = h.fetch(:k2, 2) kr1 = h.fetch(:k1) kr2 = h.fetch(:k2) ``` Problem is what happen when `h' is not a hash object (and doesn't have to_hash method). Just ignore is one option (what ary assignment do, like "a, b = 1 #=> 1, nil"). > a, *b, c:, d: 'd', **e = [1, {c: 2}] It should be: ```ruby a, (c:, d: 'd', **e) = [1, {c:2}] ``` ---------------------------------------- Feature #8895: Destructuring Assignment for Hash https://bugs.ruby-lang.org/issues/8895#change-47675 * Author: Jack Chen * Status: Open * Priority: Normal * Assignee: * Category: * Target version: ---------------------------------------- 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 { => , ��� } = # 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:(?\w+) 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/