Get immediate subdirectories in ruby
Question
I'm trying to write a simple ruby script that will copy a file to the immediate subdirectories of a directory. How would I get only the immediate subdirectories?
Solution
Dir.glob("**/")
will return an array of all paths underneath the current directory. From there you can filter the list and copy a file with File.copy(from, to)
OTHER TIPS
Assuming you only wanted the immediate subdirectories, you could use Dir['*/']
(which combines Micheal Sepcot's and glenra's answers).
If you mean to find all the immediate subdirectories (just one level below where you are), try this:
Dir.chdir("/some/path/you/want/to/check/below")
subdir_list=Dir["*"].reject{|o| not File.directory?(o)}
That is: change directory someplace, construct an array of files found there, reject those array elements that aren't directories, and return the resulting culled arrray.
Probably the best way of dealing with files in Ruby is Pathname
. It combines class methods from a few file-based modules into one nice-to-use OOP class. So you don't need to pass the value into a method like you'd have to with Dir
or File
, you can just call the method on the object itself.
Here's how to print immediate subdirectories:
require 'pathname'
puts Pathname('some/directory').children.select(&:directory?)