Created
February 23, 2014 22:02
-
-
Save microtherion/9177980 to your computer and use it in GitHub Desktop.
Perl-style autovivication for Ruby hashes and Arrays
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
#!/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