Question on hashes and init block

Hi all,

I’m using the trick someone mentioned here a few weeks ago to attach a
block to a hash so I can return an error if someone tries to access a
key which does not exist:

a = Hash.new { |key,value|
raise “Missing key [#{key}] => [#{value}]”
}
puts a[“yay”]

Strangely, this results in the following:

missing [] => [yay]
nil

In other words, I try to access a key, and the attached block complains
that that key doesn’t exist, but it treats it as a value instead.

I can work around this, obviously, because it’s consistent, but can
someone explain this to me? Is this behaviour going to change? Am I just
not understanding what is going on?

Thanks,
Luke

···


“What’s the good of having mastery over cosmic balance and knowing the
secrets of fate if you can’t blow something up?”
– Terry Pratchett, “Reaper Man”

a = Hash.new { |key,value|

                   ^^^^^^^^^

This is wrong, it's

   a = Hash.new {|hash, key| }

svg% ruby -e 'a = Hash.new {|h,k| raise "#{h.inspect} -- #{k}"}; a[1] = 2; a[2]'
-e:1: {1=>2} -- 2 (RuntimeError)
        from -e:1:in `call'
        from -e:1:in `default'
        from -e:1:in `'
        from -e:1
svg%

Guy Decoux

Ah, ok. That makes much more sense. :slight_smile: I see now.

Thank you.

Luke

···

On Sun, 11 Jan 2004, ts wrote:

a = Hash.new { |key,value|
^^^^^^^^^

This is wrong, it’s

a = Hash.new {|hash, key| }


Automatic door locks are good for…
a. security
b. convenience
c. messing with the heads of people trying to get in