Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active July 24, 2020 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/926f78768e357bda470d5fe97ded5c08 to your computer and use it in GitHub Desktop.
Save havenwood/926f78768e357bda470d5fe97ded5c08 to your computer and use it in GitHub Desktop.
An example of an autovivifying Hash refinement in Ruby.
module Autovivacious
AUTOVIVIFY = ->(hash, key) { hash[key] = Hash.new &AUTOVIVIFY }.freeze
refine Hash.singleton_class do
def new(*args, autovivify: false, **kwargs, &block)
block = AUTOVIVIFY if autovivify
super(*args, **kwargs, &block)
end
end
end
using Autovivacious
h = Hash.new autovivify: true
h[:aim][true] = 42
p h
#>> {:aim=>{true=>42}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment