Sha256: 414dcd53b8e1275d8ccfd24329a231343e6fa0f71b43cdd52a468f13cdee0626

Contents?: true

Size: 660 Bytes

Versions: 1

Compression:

Stored size: 660 Bytes

Contents

class FunctionalHash < Hash
  def [](*args)
    key = args.shift
    if fetch(key, nil).is_a? Proc
      if fetch(key).arity == 0
        fetch(key).call
      else
        args.unshift(self)
        fetch(key).call(*args)
      end
    else
      super(key)
    end
  end

  def self.enable!
    unless Hash.respond_to? :fn
      Hash.class_eval do
        def fn
          FunctionalHash.new.tap do |fh|
            self.each do |key, val|
              fh[key] = val
            end
          end
        end
      end
    end
  end

  def self.disable!
    if Hash.instance_methods.include? :fn
      Hash.class_eval { undef_method :fn }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
functional_hash-0.2.1 lib/functional_hash.rb