"Hello"}} 或者: [["Memory", [["-6ren">
gpt4 book ai didi

ruby - 在 Ruby 中将嵌套数组转换为嵌套哈希

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:44 26 4
gpt4 key购买 nike

在不知道数组维度的情况下,如何将数组转换为嵌套哈希?

例如:

[["Message", "hello"]]

到:

{{:message => "Hello"}}

或者:

[["Memory", [["Internal Memory", "32 GB"], ["Card Type", "MicroSD"]]]]

到:

{{:memory => {:internal_memroy => "32 GB", :card_type => "MicroSD"}}}

或:

[["Memory", [["Internal Memory", "32 GB"], ["Card Type", "MicroSD"]]], ["Size", [["Width", "12cm"], ["height", "20cm"]]]]

到:

{ {:memory => {:internal_memroy => "32 GB", :card_type => "MicroSD"}, {:size => {:width => "12cm", :height => "20cm" } } }

最佳答案

考虑到您的成对嵌套数组的格式,以下函数将其转换为您想要的散列

def nested_arrays_of_pairs_to_hash(array)
result = {}
array.each do |elem|
second = if elem.last.is_a?(Array)
nested_arrays_to_hash(elem.last)
else
elem.last
end
result.merge!({elem.first.to_sym => second})
end
result
end

一个较短的版本

def nested_arrays_to_hash(array)
return array unless array.is_a? Array
array.inject({}) do |result, (key, value)|
result.merge!(key.to_sym => nested_arrays_to_hash(value))
end
end

关于ruby - 在 Ruby 中将嵌套数组转换为嵌套哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15244017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com