Skip to content

Instantly share code, notes, and snippets.

@microtherion
Created February 23, 2014 22:02
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 microtherion/9177980 to your computer and use it in GitHub Desktop.
Save microtherion/9177980 to your computer and use it in GitHub Desktop.
Perl-style autovivication for Ruby hashes and Arrays
#!/usr/bin/ruby
class Array
def self.of(cclass)
return Class.new(Array) do
const_set :NESTED, cclass
def self.new(size, *args)
super(size) do |idx|
self::NESTED.new(*args)
end
end
end
end
end
class Hash
def self.of(cclass)
return Class.new(Hash) do
const_set :NESTED, cclass
def self.new(*args)
super() do |hash,key|
hash[key] = self::NESTED.new(*args)
end
end
end
end
end
if __FILE__ == $0
Arrr = Array.of Array.of Array
arrr = Arrr.new(3,3,3)
arrr[2][0][1] = true
p arrr
Harry = Array.of Hash
harry = Harry.new(10)
harry[2]['tom'] = 'dick'
p harry
Harrarr = Array.of(Array.of Hash)
harrarr = Harrarr.new(3,3)
harrarr[0][2]['oh'] = 'no'
p harrarr
Arsh = Hash.of Array
arsh = Arsh.new(5)
arsh['but'][2] = true
arsh['not'][4] = false
p arsh
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment