Created
May 21, 2013 02:25
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/
This file contains hidden or 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
# 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