Skip to content

Instantly share code, notes, and snippets.

@cyanglee
Created May 21, 2013 02:25
Show Gist options
  • Save cyanglee/5617141 to your computer and use it in GitHub Desktop.
Save cyanglee/5617141 to your computer and use it in GitHub Desktop.
There are different ways to create recursive hash in ruby. I found two tricks from here: http://metaskills.net/2012/03/12/store-configurable-a-lesson-in-recursion-in-ruby/
# ruby recursive hash examples
# http://metaskills.net/2012/03/12/store-configurable-a-lesson-in-recursion-in-ruby/
# trick 1
class RecursiveHash < Hash
Recursive = lambda { |h,k| h[k] = h.class.new }
def initialize
super(&Recursive)
end
end
hash = RecursiveHash.new # => {}
hash.class # => RecursiveHash
hash[:foo] # => {}
hash[:foo].class # => RecursiveHash
hash[:a][:b][:c] # => {}
hash # => {:foo=>{}, :a=>{:b=>{:c=>{}}}}
loader = lambda do |hash, key, value|
if value.is_a?(Hash)
value.each { |k,v| loader.call(hash.send(key), k, v) }
else
options.send "#{key}=", value
end
end
data.each { |k,v| loader.call(config, k, v) }
#trick 2
my_hash = Hash.new { |h, k| h[k] = Hash.new(&my_hash.default_proc) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment