
class Hash

  # Define a fallback object for #fetch and #[].
  #
  #   f = Hash[:b=>2]
  #   h = Hash[:a=>1].having_fallback(f)
  #   h[:b] => 2

  def having_fallback(parent=nil)
    @fallback = parent
    unless @fallsback
      def self.[](key)
        return @fallback[key] if @fallback and not key?(key) rescue super
        super
      end
      def self.fetch(key, *args, &blk)
        return @fallback.fetch(key, *args, &blk) if @fallback and not key?(key) rescue super
        super
      end
      @fallsback = true
    end
    self
  end

  attr_accessor :fallback

end
