Modifying Hash Default Value

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?

···

--
Lou

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

:wink:

James Edward Gray II

···

On May 8, 2006, at 3:44 PM, Louis J Scoras wrote:

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?

Heh, I knew it would end up being something obvious. Still, don't do
what I did =)

Thanks James!

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

robert

···

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 =)

--
Have a look: http://www.flickr.com/photos/fussel-foto/

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.

···

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. :slight_smile: