Assuming I have directory structure like
MyDir
+ Music
+ Movies
+ Pictures
+ Videos
How do I find directory called Pictures using Ruby?
You could capture the output of Dir.pwd
and then use ls
, like:
files = `ls #{Dir.pwd}`
p files # "Movies\nMusic\nPictures\nVideos\n"
p files.split.include? 'Pictures' # true
Or also using Open3 :
require 'open3'
files, = Open3.capture2('ls', Dir.pwd)
p files # "Movies\nMusic\nPictures\nVideos\n"
p files.split.include? 'Pictures' # true
Consider you're inside the MyDir
folder.
Dir['MyDir/Pictures']
Unfortunately, it this won't return you an object, you can operate with, just an array. So if you want iterate over files in this directory, you should do something like the following
Dir['MyDir/Pictures/*'].each do |file_name|
# do something
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.