Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #7411
| From | Doc O'Leary <droleary@2017usenet1.subsume.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: * in { |key, value| value * 2 } |
| Date | 2019-07-16 19:44 +0000 |
| Organization | Subsume Technologies, Inc. |
| Message-ID | <qgl9ek$bcf$1@dont-email.me> (permalink) |
| References | <qfvn84$bp1$1@reader1.panix.com> <qgfilp$q3h$1@dont-email.me> <qgkqde$e57$1@reader1.panix.com> |
For your reference, records indicate that
dreamer <dreamer@panix.com> wrote:
> Here is an example I found on stackoverflow (https://stackoverflow.com/questions/5215713/ruby-what-is-the-easiest-method-to-update-hash-values)
>
> h = { 1 => 10, 2 => 20, 5 => 70, 8 =>90, 4 => 34 }
>
> which the writer would like to change to:
>
> h = { 1 => foo(10), 2 => foo(20), 5 => foo(70), 8 => foo(90), 4 => foo(34) }
>
> and the "best" answer was the line above:
>
> hash.update(hash) { |key, value| value * 2 }
>
> My confusion was really about the "value * 2"
Well, in that case the answer did confuse the issue a bit by giving that
instead of “foo(value)” to correspond with the question.
> "Note that we're effectively merging hash with itself. This is
> needed because Ruby will call the block to resolve the merge
> for any keys that collide, setting the value with the return
> value of the block."
>
> I was wondering why this would be better/different than just doing an
> update to the hash and key.
By doing what instead? You certain *could* just iterate through using an
enumerator, making assignments explicitly. But using a block with the
update method is a much more convenient way to accomplish the task (and
generally why so many generic Enumerable methods accept blocks).
> And what is meant by 'resolving the merge
> for any keys that collide'.
That’s just the way the update method works. Its “normal” use is to merge
two different hashes, and the block is only run to resolve the case where
there are keys that exist in both. But used against itself, *all* entries
will match, and thus be changed by the code in the given block.
--
"Also . . . I can kill you with my brain."
River Tam, Trash, Firefly
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar
* in { |key, value| value * 2 } dreamer <dreamer@panix.com> - 2019-07-08 15:24 +0000
Re: * in { |key, value| value * 2 } Doc O'Leary <droleary@2017usenet1.subsume.com> - 2019-07-14 15:44 +0000
Re: * in { |key, value| value * 2 } dreamer <dreamer@panix.com> - 2019-07-16 15:27 +0000
Re: * in { |key, value| value * 2 } Doc O'Leary <droleary@2017usenet1.subsume.com> - 2019-07-16 19:44 +0000
Re: * in { |key, value| value * 2 } dreamer <dreamer@panix.com> - 2019-07-17 23:21 +0000
csiph-web