Last active
July 24, 2020 20:34
-
-
Save havenwood/926f78768e357bda470d5fe97ded5c08 to your computer and use it in GitHub Desktop.
An example of an autovivifying Hash refinement in Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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