Forum: Ruby Modifying Hash Default Value

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
51a34236538906ab994cf9f2e533d14d?d=identicon&s=25 Lou Scoras (ljscoras)
on 2006-05-08 22:47
(Received via mailing list)
Don't do this...This one bit me hard =)

    hash = Hash.new( [ ] )
    hash[:new_key] << 3

    hash.length             # => 0 ouch
    hash.keys                # => [ ] doh!

    # this why this was painful...
    hash[:new_key] # => [ 3 ]

    hash[:another_key] # => [ 3 ]

So anyway, is there no way to have this do what I mean? or do I have
to initialize it seperately?

    hash[:new_key] ||= [ ]
    hash[:new_key] << 3

I'm having a total mental lapse, but I know using the block form won't
help either, i.e.:

    hash = Hash.new { [ ] }

Any thoughts?
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-05-08 22:50
(Received via mailing list)
On May 8, 2006, at 3:44 PM, Louis J Scoras wrote:

>
>
>    hash = Hash.new { [ ] }
>
> Any thoughts?

Hash.new { |hash, key| hash[key] = Array.new }

;)

James Edward Gray II
51a34236538906ab994cf9f2e533d14d?d=identicon&s=25 Lou Scoras (ljscoras)
on 2006-05-08 23:05
(Received via mailing list)
Heh, I knew it would end up being something obvious.  Still, don't do
what I did =)

Thanks James!
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2006-05-09 09:41
(Received via mailing list)
2006/5/8, Louis J Scoras <louis.j.scoras@gmail.com>:
> Heh, I knew it would end up being something obvious.  Still, don't do
> what I did =)

This comes up here roughly every three days. So you're not alone if
that comforts you. :-)

robert
51a34236538906ab994cf9f2e533d14d?d=identicon&s=25 Lou Scoras (ljscoras)
on 2006-05-09 14:54
(Received via mailing list)
On 5/9/06, Robert Klemme <shortcutter@googlemail.com> wrote:
> This comes up here roughly every three days. So you're not alone if
> that comforts you. :-)

Heh.  Nope, I'm almost never comforted by other people's misfortunes,
which is partly why I posted this.

It was actually a pretty basic (read stupid) error on my part, but my
biggest blunder was actually /not reading the documentation/.  As soon
as I saw a block with two parameters associated with a hash, I
immediately assumed that it was iteration with key/value pairs, which
of course makes absolutely no sense in this context.  Had I read the
documentation for the hash constructor I would have seen that it
passes the entire hash with the failed key, at which point the
solution comes quite naturally as James pointed out above.
This topic is locked and can not be replied to.