Skip to content

Instantly share code, notes, and snippets.

@havenwood

havenwood/autovivicious.rb

Last active Jul 24, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.