ruby动态哈希键

时间:2016-07-14 08:57:06

标签: ruby json hash amazon-s3

我有一个s3文件的路径列表,形成一个像

这样的桶
a/b/c
a/b/c/d.txt
a/d/e.txt

有没有办法可以创建上述信息的json表示,我正在寻找像

这样的东西

{:a=>{:b=>{:c=>[d.txt]},:d=>[e.txt]}}

我使用eval生成了动态密钥名称,但我无法做到

eval(a[:b]X) where X is something like [:c]

提前致谢

1 个答案:

答案 0 :(得分:2)

files = %w(a/b/c.txt a/b/c/d.txt a/d/e.txt)
files.reject do |f| # first of all, remove redundant dirs
  files.any? { |ff| ff != f && ff.start_with?(f) }
end.each_with_object({}) do |f, memo|
  *path, file = f.split('/')
  bucket = path.inject(memo) { |acc, k| acc[k] ||= {} }
  (bucket[:files] ||= []) << file
end
#⇒ {
#  "a" => {
#    "b" => {
#         "c" => {
#        :files => [
#          [0] "d.txt"
#        ]
#      },
#      :files => [
#        [0] "c.txt"
#      ]
#    },
#    "d" => {
#      :files => [
#        [0] "e.txt"
#      ]
#    }
#  }
# }