ruby - Automatic nested hash keys with ability to append value -
i have arbitrary list of file names i'd sort hash. i'd like this:
## example file name 'hello.world.random_hex" file_name_list.each |file| name_array = file.split('.') files[name_array[0].to_sym][name_array[1].to_sym] << file end
those keys may not exist , i'd them automatically created default value of [] << works expected. final files hash like:
{ :hello => { :world => [ "hello.world.random_hex", "hello.world.other_random_hex" ] } }
how can initialize files accomplish this?
if there 2 levels of keys this, can using block form of hash.new:
files = hash.new {|k,v| k[v] = hash.new {|k,v| k[v] = [] }}
(on other hand, if keys can nested arbitrary depth, harder because hash can't know whether value nonexistent key should hash or array @ time accessed.)
Comments
Post a Comment