Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of an autovivifying Hash refinement in Ruby.
module Vivification
refine Hash.singleton_class do
def new(*args, autovivify: false, &block)
return Hash.new(&VIVIFIED_PROC) if autovivify
super(*args, &block)
end
end
end
module Autovivicious
include Vivification
VIVIFIED_PROC = ->(hash, key) { hash[key] = Hash.new &VIVIFIED_PROC }.freeze
private_constant :VIVIFIED_PROC
end
using Autovivicious
include Autovivicious
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.