【问题标题】:Determine name of last subfolder in a path (Ruby)确定路径中最后一个子文件夹的名称(Ruby)
【发布时间】:2022-09-23 23:26:00
【问题描述】:

红宝石新手。我试图弄清楚如何获取文件夹的名称。我有这个:

path = Dir[\"#{some_base_path}/*/*\"]

这给了我这样的东西:

path: [\"/tmp/animals/cats/Fluffy\"]

我想要知道最后一个子文件夹的名称——在本例中为Fluffy

我尝试过PathnameFile.basename 的变体,但我总是遇到no implicit conversion of Array into String (TypeError) 错误。

最好的方法是什么?

  • 好吧,你有一个字符串数组。你想申请File.basename et al to元素数组,而不是数组本身。
  • 例如,不确定它是否适合您的用例,但您可以做的一件事是path = Dir[\"#{some_base_path}/*/*\"].first
  • 如果有多个这样的文件夹怎么办?

标签: ruby


【解决方案1】:
# Get array of subdirectories arrays
directories =
  Dir[pattern].
    filter_map { |filename| filename.split("/") if File.directory?(filename) }

# Get maximum subdirectories depth
max_depth = directories.max_by(&:size).size

# Get all subdirectories (tree leaves) with maximum depth
directories.filter_map { |dirs| dirs.last if dirs.size == max_depth }

【讨论】:

    【解决方案2】:

    你已经有了你的道路。编程语言中有一个巧妙的东西叫做Tokenization

    您可以通过单个字符或更多字符拆分字符串。

    从您的阵列开始

    paths = ["/tmp/animals/cats/Fluffy"]
    => ["/tmp/animals/cats/Fluffy"]
    

    您可以采用第一个元素(这是您的路径字符串)

    path = paths.first
    => "/tmp/animals/cats/Fluffy"
    

    tokenize it with ruby

    tokens = path.split("/")
    => ["", "tmp", "animals", "cats", "Fluffy"]
    

    然后返回“令牌”数组的最后一个元素。

    tokens.last
    => "Fluffy"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 2013-06-21
      • 2018-03-20
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多