views:

87

answers:

2

I wanted to extend the Hash class so that all hashes get same default_proc when they're created. So I put this in my file:

class Hash
  def initialize
    self.default_proc = proc { |hash, key| raise NameError, "#{key} is not allowed" }
  end
end

This works fine if I use this syntax

h = Hash.new

but not if I use

h = {}

Playing with it, it seems that the latter syntax doesn't call initialize. Is there an "iron-clad" way to achieve setting the default_proc for all hashes?

A: 

Yes, {} won't call the initialize method, as you can't pass a block to {}:

# This will issue an error
h = {}{#some block code}

However you still can pass blocks to the new method:

h = Hash.new { |hash, key| raise NameError, "#{key} is not allowed" }
khelll
+1  A: 

I suppose you could just intercept []

class Hash
  alias realGet []
  def [](x)
    t = realGet(x)
    if t == nil
      puts 'intercepted'
    end
    t
  end
end
DigitalRoss
cool! that never would have occurred to me. the good news is, it'll be a looooooong time before I'm bored with ruby. ;)