From: "Jesús Gabriel y Galán" Date: 2008-12-15T23:03:20+09:00 Subject: Re: string to hash On Tue, Dec 9, 2008 at 8:33 PM, Brian Adkins wrote: > Jens -- writes: > >> Hi All, >> >> I am in the need of a method that does the following: >> >> get 2 arguments a string and an integer (int_val). >> The string has the following form "a.b.c.d" >> >> the method should return a nested hash like that: >> >> { :a => { :b => { :c => { :d => int_val } } } } >> >> Hmmmm I am not rubyist enough to solve that elegant (or not at all :-/). > > Dave's solution is a good one & "idiomatic Ruby", and it should be > efficient since it spends much time in C code. Sorry to answer after so long, but I wanted to give another version: irb(main):059:0> def nested_hash s, i irb(main):060:1> hash = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)} irb(main):061:1> terms = s.split(".") irb(main):062:1> temp = terms[0..-2].inject(hash) {|acc,val| acc[val.to_sym]} irb(main):063:1> temp[terms[-1].to_sym] = i irb(main):064:1> hash irb(main):065:1> end => nil irb(main):066:0> nested_hash "a.b.c.d", 55 => {:a=>{:b=>{:c=>{:d=>55}}}} I am so fond of the arbitrarily nested hash construct :-). Jesus.