gpt4 book ai didi

Ruby 如何展开哈希表并连接其值

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:54 25 4
gpt4 key购买 nike

我有下表的 yaml 格式:

:first_directory:
:component1:
- component1.c
- component1.h
:component2:
:component2_A:
:src:
- component2_A.c
:inc:
- component2_A.h

当我打印哈希的内容时,我得到:

{:first_directory=>{:component1=>["component1.c", "component1.h"], :component2=>{:component2_A=>{:src=>["component2_A.c"], :inc=>["component2_A.h"]}}}}

现在我希望能够创建字符串来连接哈希层次结构的所有可能值,并使用字符拆分它。我想要生成的字符串如下所示:

first_directory/component1/component1.c
first_directory/component1/component1.h
first_directory/component2/component2_A/src/component2_A.c
first_directory/component2/component2_A/inc/component2_A.h

实现这一目标的最干净、最好的方法是什么?

最佳答案

这种方法应该最有效:

def print_hash(hash_node, prev_string=nil)
if hash_node.class == Array
hash_node.each {|element| puts "#{prev_string}#{element}"}
else # it is an inner hash
hash_node.each do |key, value|
print_hash(value, "#{prev_string}#{key}/")
end
end
end

print_hash(content_as_a_hash)

测试运行:

content_as_a_hash = {:first_directory=>{:component1=>["component1.c", "component1.h"], :component2=>{:component2_A=>{:src=>["component2_A.c"], :inc=>["component2_A.h"]}}}}

print_hash(content_as_a_hash)

结果:

first_directory/component1/component1.c
first_directory/component1/component1.h
first_directory/component2/component2_A/src/component2_A.c
first_directory/component2/component2_A/inc/component2_A.h

关于Ruby 如何展开哈希表并连接其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54520530/

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