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

From: 6ftdan@...
Date: 2015-11-18 18:41:10 UTC
List: ruby-core #71562
Issue #11690 has been updated by Daniel P. Clark.


I was thinking of what word(s) may best clarify this and not conflict with other potential uses.  One issue about the word `assigned` is it seems like `self = ` or `replace`.  I at first was thinking of `to_be` ... but that's sounds more like a promise of the future and each method would have to end in `ed` like so `x.to_be.updated = a: 1`.  To avoid using a promise form and complex `ed` handling I was thinking of just `to`; `x.to.update`.  But I don't think this is clear enough.  So I have found the shortest thing I can think of that matches the statement `to_be_assigned_with`, and that is `apply`.  It's short, simple, clear, and reveals to anyone that more is being done here.

To copy from Nobuyoshi's idea

~~~Ruby
class Applicable
  def initialize(obj)
    @target = obj
  end
  def method_missing(m, *args)
    @target.__send__(m.to_s.chomp('='), *args)
  end
  def respond_to_missing?(m)
    @target.respond_to?(m.to_s.chomp('='))
  end
end
module Kernel
  def apply
    Applicable.new(self)
  end
end

x = {a: 1, b: 2}

x.apply.update, y ,z = {c: 3}, 6, 7
p x
~~~

Arguably I think this is just as clear as `to_be_assigned_with`, and is different enough for people to notice that something else is going on here.  That should be enough.

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

* 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