Built in way to list directories in a directory in ruby

前端 未结 2 1163
别跟我提以往
别跟我提以往 2021-02-05 10:41

Is there a cleaner built-in way to do this?

ree> Pathname.new(\'/path/to\').children.select{|e| e.directory?}.map{|d| d.basename.to_s}
 => [\"test1\", \"t         


        
相关标签:
2条回答
  • 2021-02-05 10:56
    Pathname.glob("/path/to/*/").map { |i| i.basename.to_s }
    
    0 讨论(0)
  • 2021-02-05 10:58

    Starting from Chandra's answer, depending on whether you need or not the full path, you can use

    Dir['app/*/']
    # => ["app/controllers/", "app/helpers/", "app/metal/", "app/models/", "app/sweepers/", "app/views/"
    
    Dir['app/*/'].map { |a| File.basename(a) }
    # => ["controllers", "helpers", "metal", "models", "sweepers", "views"]
    

    If you use Ruby >= 1.8.7, Chandra's answer can also be rewritten as

    Pathname.glob('app/*/').map(&:basename)
    # you can skip .to_s unless you don't need to work with strings
    # remember you can always use a pathname as string for the most part of Ruby functions
    # or interpolate the value
    
    0 讨论(0)
提交回复
热议问题