Initialize all hashes with default_proc

I wanted to extend the Hash class so that all hashes come out the same default_proc

when they were 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 great if I use this syntax

h = Hash.new

      

but not if i use

h = {}

      

Playing with this it seems that the latter syntax does not call initialization. Is there a hardcoded way to get default_proc

all hashes set?

+2


source to share


2 answers


I guess you can just intercept []



class Hash
  alias realGet []
  def [](x)
    t = realGet(x)
    if t == nil
      puts 'intercepted'
    end
    t
  end
end

      

+1


source


Yes, {}

it won't call the method initialize

, since you can't pass a block {}

:

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

      



However, you can still pass blocks to the new method:

h = Hash.new { |hash, key| raise NameError, "#{key} is not allowed" }

      

0


source







All Articles