SephirothSpawn wrote:
I came up with some pretty cool method modifications for the Hash class that allows you to read and set multi-dimensioned hashes without the work it had before. It also allows you to use classes with [] and []= methods.
...
...
Couldn't this be done simply with default values? Like so:
- MULTI_HASH = Proc.new { |hash, key| hash[key] = Hash.new(&MULTI_HASH) }
- @hash = Hash.new(&MULTI_HASH)
- @hash[0][2] = 4
- print @hash # {0=>{2=>4}}
Expand to see the code.
Haven't tested it, and it could be tricky since MULTI_HASH is recursive. It might be better done as a class with a recursive initializer (again, not tested):
- class Multi_Hash
- def initialize(depth = 0, default = nil, &default_block)
- if depth == 0
- super(default, &default_block)
- else
- super do |hash, key|
- hash[key] = Multi_Hash(depth - 1, default, &default_block)
- end
- end
- end
- def has_key?(*args)
- return false if args.size == 0
- return super(args[0]) if args.size == 1
- return self[args.shift].has_key(*args)
- end
- end
Expand to see the code.