[ruby-core:71507] [Ruby trunk - Feature #11690] Update Hash during multiple assignment

From: 6ftdan@...
Date: 2015-11-16 14:17:10 UTC
List: ruby-core #71507
Issue #11690 has been updated by Daniel P. Clark.


I'm not sure the opts[*] is a good idea.  You have have current splat behavior with multiple assignment.

~~~ruby
a, *, c = [1,2,3,4,5]
a
# => 1
c
# => 5
~~~

And the opts[*] is unclear about what it is and what it expects.  It could be a Proc.

~~~ruby
prc = proc {|b,c,d| b+c+d }
# if [*] were implemented
a, prc[*], c = [1,2,3,4,5]
~~~

As far as I know **Hash** is the only core object with an **update** method.  And in other cases where **update** is used, such as in Rails' ActiveRecord, a Hash is the expected input.  So when the **update** method is called it is generally understood to be expecting a **Hash** object.

Implementing [*] would be much more work that simply implementing `Hash#update=`

I was thinking about suggesting `Hash#merge!=` as well but Ruby syntax does not allow the equals sign after and exclamation point.  So I have chosen to only suggest `Hash#update=`

~~~ruby
class Hash
  def update=(h)
    update(h)
  end
end
~~~

----------------------------------------
Feature #11690: Update Hash during multiple assignment
https://bugs.ruby-lang.org/issues/11690#change-54879

* Author: Daniel P. Clark
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
Given that we can assign multiple variables at once

~~~ruby
a,b,c = 1,2,3
~~~

It would be nice to be able to update a Hash during multiple assignment rather than replacing it.  Currently

~~~ruby
x = {a: 1, b: 2}
x, y ,z = {c: 3}, 6, 7
x
# => {c: 3}
~~~

What I propose is adding `Hash#update=` to permit updating during multiple assignment.

~~~ruby
class Hash
  def update=(h)
    update(h)
  end
end

x = {a: 1, b: 2}

x.update, y ,z = {c: 3}, 6, 7
x
# => {a: 1, b: 2, c: 3}
~~~

This would be most useful in scenarios where a method or proc return multiple values.  When the method returns the values we don't normally know the key outside where the hash assignment is.

~~~ruby
example = proc { [{:hi => :hello}, 5] }

hash = {}

# Currently in Ruby with an Unknown key multiple assignment isn't an option
hash[????], current = example.call

# We currently have to two step it
result, current = example.call
hash.update(result)
~~~

But with `Hash#update=` we don't have to know the key.



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

In This Thread

Prev Next