Question on hashes and init block

L

Luke A. Kanies

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
 
T

ts

L> 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
 
L

Luke A. Kanies

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

This is wrong, it's

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

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

Thank you.

Luke
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top