Issue #8895 has been updated by boris_stitnicky (Boris Stitnicky).


@whitequark: Hi whitequark, you here? Let me raise my commendations to you for your parser gem!

As for the issue at hand, why not just say:
{ name: "JohnSmith", age: 42 }.!
and have the assigment done:
name = "JohnSmith"
age = 42

If you want the assignment done to diferent variables, why not define Hash#slice one step further:
{ n: "JohnSmith", a: 42, foo: "bar" }.slice( name: :n, age: :a ) # produces { name: "JohnSmith", age: 42 }
and then
{ n: "JohnSmith", a: 42, foo: "bar" }.slice( name: :n, age: :a ).!
produces the desired assignment:
name = "JohnSmith"
age = 42

I hope that .! syntax proposal doesn't suck too hard! It might be a general way of making objects perform assignments to local variables. I'm concerned about feature creep, though.

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

Author: chendo (Jack Chen)
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


=begin
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?
=end



-- 
http://bugs.ruby-lang.org/