ruby - 如何在 Ruby 中通过数组存储和检索哈希

标签 ruby hash

我想构建一个用于存储目录的哈希。我想要多个级别的 key 。在比赛点,我想要一个文件数组。它就像计算机上的目录结构。看来哈希是执行此操作的最佳方法。

鉴于我有一组文件夹["folder1", "folder1a", "folder1ax"],我该如何:

  1. 使用文件夹结构作为键、文件作为数组中的值来设置哈希,并且
  2. 使用文件夹结构查询哈希值?

我使用它来解析 URL 以在文件夹结构中显示它们,这与在 Rails 应用程序中转储到 JSTree 非常相似。因此,如果您有更好的替代方案来显示 5000 个 URL,并且与 Rails View 配合得很好,请提供替代方案。

最佳答案

这是一个起点:

dirs = %w(Downloads)
Hash[ dirs.map{ |dir| [dir, Dir.glob("#{dir}/*")] } ]

这是结果:

{"Downloads"=> ["Downloads/jquery-ui-1.9.1.custom.zip", ... ] }

您可以改进代码使其递归,从数组结果中删除文件夹名称...这是递归实现的示例:

class Dir
  def self.ls_r(dir)
    Hash[ dir,
      entries(dir).reject{ |entry| %w(. ..).include?(entry) }.map do |entry|
        entry_with_dir = File.join(dir, entry)
        File.directory?(entry_with_dir) ? ls_r(entry_with_dir) : entry
      end ]
  end
end

puts Dir.ls_r('~/Downloads').inspect 
#=> { "Downloads" => ["file1", {"Downloads/folder1"=>["subfile1"], ... ] } ... }

请注意,这不是最好的实现,因为递归没有考虑到子文件夹键应该相对于各自的父键;要解决此问题,应通过递归维护此信息:

class Dir
  def self.ls_r(dir, key_as_last_path_component = false)
    Hash[ (key_as_last_path_component ? File.split(dir).last : dir),
      entries(dir).reject{ |entry| %w(. ..).include?(entry) }.map do |entry|
        entry_with_dir = File.join(dir, entry)
        File.directory?(entry_with_dir) ? ls_r(entry_with_dir, true) : entry
      end ]
  end
end

puts Dir.ls_r('~/Downloads').inspect
#=> { "Downloads" => ["file1", {"folder1"=>["subfile1"], ... ] } ... }

现在子文件夹是相对于其父键的。

关于ruby - 如何在 Ruby 中通过数组存储和检索哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13529865/

相关文章:

arrays - Ruby 最长回文子串函数中的奇怪输出

ruby-on-rails - 在学习 Ruby On Rails 教程之后,无法将用户添加到数据库

ruby - 条件语句出现在表达式之前还是之后有关系吗?

ruby - 将 ActiveRecord 与 DelegateClass 结合使用

java - MD5 hashing在IOS和windows中相同,在java中不同

python - 如何比较嵌套的字典

mysql - 如果我知道分布将不相等,如何计算哈希中的桶数?

c++ - 在 double 组上使用 unordered_map

perl - 在散列中添加 Getopt::Long 选项,即使使用重复说明符

ruby - Rails 3.2 遍历数组