I have to manipulate a deeply nested hash (5 or six levels) in Ruby. For example, I need to swap the 3rd and 4th levels like so, from:
a[b][c][d][e] = []
to:
开发者_JAVA百科a[b][d][c][e]= []
Can anyone point me to algorithms that will help me? I'm not lazy, just under a time constraint.
Unless I am terribly tired, you'd get away with something like so:
result = Hash.new
a.each do |b, ab|
result[b] ||= Hash.new
ab.each do |c, abc|
abc.each do |d, abcd|
(result[b][d] ||= Hash.new)[c] = abcd
end
end
end
a = result
Now, I'm not saying this is the most efficient way of working it out.
Since it came to light that you're parsing XML, I strongly suggest that you don't roll your own solution. REXML is one option for parsing XML in Ruby.
精彩评论