ruby - Access variable hash depth values with square brackets notation -
given hash:
hash1= { node1: { node2: { node3: { node4: { node5: 1 } } } } }
we access inside nodes square brackets this:
hash1[:node1][:node2][:node3][:node4]
now have hash know nested xml response soap webservice, neither depth of hash nor names of nodes stay same. nice if ask user of application hash depth , store in variable. , able hash1[:hash_depth]
, achieve same result above.
i have accomplished want following code:
str = 'node1,node2,node3,node4' str_a = str.split(',') hash_copy = hash1 str_a.each { |s| hash_copy = hash_copy.[](s.to_sym) } hash_copy => {:node5=>1} hash1[:node1][:node2][:node3][:node4] => {:node5=>1}
that asking user enter hash depth separated commas, store in string, split it, make array, clone original hash, go down each level , modify hash till desired node. there way square brackets notation , using variable store depth without modifying hash or needing clone it?
edit: answered following (can't see post anymore???)
hash_depth="[:node1][:node2][:node3][:node4]" eval "hash1#{hash_depth}"
although eval
need, there approach, since have working code comma-separated list:
hash_depth="[:node1][:node2][:node3][:node4]" csh = hash_depth.gsub(/\a\[:|\]\[:|\]\z/, { '][:' => ',' }) #⇒ "node1,node2,node3,node4"
and free apply existing function csh
.
Comments
Post a Comment