开发者

Manipulating a hash in Ruby

开发者 https://www.devze.com 2023-02-18 08:08 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消