Istvan
Istvan

Reputation: 8562

How to use a dynamic variable name for nested hashes in Ruby?

How could I do something similar in Ruby (1.8)? My aim is to use a variable for the key in the hash where I assign a variable.

@keys=""
my_hash = Hash.new { |h,k| h[k]=Hash.new(&h.default_proc) }

line="long:keys:are:here:many:of:them:dont:know:how:much"

line.split(':').each { |x| 
  @keys=@keys+'["'+x+'"]'
}

my_hash#{@keys}=1

#I would like to assign a variable for the following.
# my_hash["long"]["keys"]["are"]["here"]["many"]["of"]["them"]["dont"]["know"]["how"]["many"]=1

Upvotes: 2

Views: 967

Answers (1)

Chris Bunch
Chris Bunch

Reputation: 89823

Loop through the items to nest through, creating a new hash for each and putting it inside the previous hash. Since you want to assign a variable to the last one, you can keep pointers to each as you construct it and once you have them all, you have a pointer to the last one. The code looks like this:

hash = {}
line="long:keys:are:here:many:of:them:dont:know:how:much"

current_depth = hash
subhash_pointers = []
line.split(':').each { |x|
  current_depth[x] = {}
  current_depth = current_depth[x]
  subhash_pointers << current_depth
}

puts hash.inspect

subhash_pointers[-1] = 1
puts subhash_pointers.join(' ')

Which produces this output (namely the big hash you were looking for and pointers to all the subhashes, with the last one being 1 as you requested):

{"long"=>{"keys"=>{"are"=>{"here"=>{"many"=>{"of"=>{"them"=>{"dont"=>{"know"=>{"how"=>{"much"=>{}}}}}}}}}}}}

keysareheremanyofthemdontknowhowmuch areheremanyofthemdontknowhowmuch heremanyofthemdontknowhowmuch manyofthemdontknowhowmuch ofthemdontknowhowmuch themdontknowhowmuch dontknowhowmuch knowhowmuch howmuch much 1

Upvotes: 1

Related Questions