Поскольку строка 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"]