将数组散列到类似文件路径的数组

时间:2014-02-28 08:24:02

标签: ruby hash

这是数组散列的结构:

[
    {
      "key1" => [
            "value1",
            {"key2" => ["value2"]},
            {"key3" =>  [
                              "value3",
                              {
                                "key4" => "value4"
                              }
                        ]
            }                 
       ]
    },
    {
        "anotherKey1" => [],
    }
]

我想要像filepaths那样的结构所需的输出:

/key1/value1
/key1/key2/value2
/key3/value3
/key3/key4/value4

如果不发明轮子怎么办呢?简单的递归可能会有所帮助,但是有没有现成的模块?

2 个答案:

答案 0 :(得分:1)

我认为你不会重新发明任何轮子来做到这一点。您希望遍历数组和散列的嵌套结构,并根据是否为Array或Hash,对元素做出完全不同的反应。没有库函数可以完全满足您的要求,因为您需要使用块来改变多个事物,以便像您希望的那样灵活。

简而言之:编写递归函数来执行此操作。

(顺便说一下:你的数据结构的顶层是一个哈希数组,而不是数组的哈希...)

答案 1 :(得分:0)

我决定写自己的轮子(感谢Patru,投票)。

我有这个功能:

def flat_hash_of_arrays(hash,string = "",delimiter="/",result = [])

    # choose delimiter
    hash.each do |key,value|

        # string dup for avoid string-reference (oh, Ruby)
        newString = string + delimiter + key 
        # if value is array     
        if value.is_a?(Array)

            # if array not empty
            value.each do |elementOfArray|

                # if a string, I dont need recursion, hah
                if elementOfArray.is_a?(String) 
                    resultString = newString + delimiter + elementOfArray                   
                    # add new object
                    result << resultString
                end

                # if a hash, I need recursion
                if elementOfArray.is_a?(Hash)
                    flat_hash_of_arrays(elementOfArray,newString,delimiter,result)
                end                     

            end                     

        end     
    end
end

并测试它:

flatten_hash = {
      "key1" => [
            "value1",
            {"key2" => ["value2"]},
            {"key3" =>  [
                              "value3",
                              {
                                "key4" => "value4"
                              }
                        ]
            },      
            "value4",
            {
                "key4" => ["value5"],
            }           
       ]
    }

result = []
flat_hash_of_arrays(flatten_hash,"","/",result)

puts result

输出是:

/key1/value1
/key1/key2/value2
/key1/key3/value3
/key1/value4
/key1/key4/value5

细!