Modifying Hash Default Value


#1

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?


#2

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 }

:wink:

James Edward G. II


#3

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

Thanks James!


#4

On 5/9/06, Robert K. removed_email_address@domain.invalid wrote:

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

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.


#5

2006/5/8, Louis J Scoras removed_email_address@domain.invalid:

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

robert