【问题标题】:Get all file names in a directory with ruby [duplicate]使用ruby获取目录中的所有文件名[重复]
【发布时间】:2012-09-25 00:00:16
【问题描述】:

可能重复:
Get names of all files from a folder with Ruby

我是Ruby 的新手,我正在尝试从特定目录中获取所有文件名。只有一个级别,只需要获取整个名称列表。我怎么做?我查看了有关该主题的其他一些帖子,但没有任何帮助。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    列出当前目录中的所有条目:

    Dir.entries('.')
    

    【讨论】:

    • 值得一提的是,这会返回一个字符串数组,其中还包含'.''..'
    【解决方案2】:
    Dir.new('.').each {|file| puts file }
    

    请注意,这将包括 .和..

    【讨论】:

      【解决方案3】:

      您可以使用 Dir#glob 返回特定目录的特定文件名

      Dir.glob("*") #Get all filenames on current directory
      Dir.glob("somedirectory/*") #Get all filenames on some directory
      Dir.glob("somedirectory/*.php") #Get specific files with specific extension on some directory
      

      【讨论】:

        【解决方案4】:

        似乎 OP 要求仅列出文件,而不是目录。

        Dir['path/to/dir/*'].select { |e| File.file?(e) }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-10
          • 1970-01-01
          • 2020-08-29
          • 2015-02-28
          • 2011-02-24
          • 1970-01-01
          • 2013-04-07
          • 2017-08-20
          相关资源
          最近更新 更多