红宝石如何展开一个哈希表并连接它的价值

问题描述 投票:3回答:2

我有一个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

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

ruby
2个回答
5
投票

这种方法可以很好的工作方式:

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

3
投票

作为YAML字符串使用缩进,以指示结构,可以通过直接在串操作,采用堆获得期望的结果。

arr=<<_.lines
:first_directory:
 :component1:
  - component1.c
  - component1.h
 :component2:
  :component2_A:
   :src:
    - component2_A.c
   :inc:
    - component2_A.h
_
  #=> [":first_directory:\n",
  #    " :component1:\n",
  #    "  - component1.c\n",
  #    "  - component1.h\n",
  #    " :component2:\n",
  #    "  :component2_A:\n",
  #    "   :src:\n",
  #    "    - component2_A.c\n",
  #    "   :inc:\n",
  #    "    - component2_A.h\n"] 

def rollup(stack)
  stack.transpose.last.join('/')
end

stack = []

arr.each_with_object([]) do |line,arr|
  indent = line =~ /\S/
  line.gsub!(/[:\s-]/, '')
  if stack.any? && indent <= stack.last.first
    arr << rollup(stack)
    stack.select! { |ind,_| ind < indent }
  end
  stack << [indent, line]
end << rollup(stack)
  #=> ["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"] 
© www.soinside.com 2019 - 2024. All rights reserved.