Reputation: 793
I'm trying to return a list of files for a directory using the following code:
Dir[directory]
The issue I'm having is this appears to always take the url as relative to the project location. For example passing '*' into Dir returns an array containing my Gemfile etc.. I want to be able to get a list of files for directories such as /Users/jason/Pictures
however when i pass in /Users/jason/Pictures/*
I am returned an empty array.
Any pointers would be greatly appreciated. Thanks.
Upvotes: 0
Views: 281
Reputation: 160551
Try:
Dir['/Users/jason/Pictures/*']
If there are files or directories embedded in that path you'll get an array back from Dir[]
. If you don't, and you're sure there are files in the directory, then there's something wrong, but it's most likely in the glob string you gave it. Confirm it's the right path by moving to it and using pwd
to see what the OS thinks it is. Dir[]
doesn't return an error if the glob string isn't valid, it just returns an empty array.
You could try using File.exist?('glob string without *')
and see whether that path exists before trying to iterate it.
On my machine, running this in IRB in my home directory:
Dir['./vim/bundle/*']
Returns:
[
[ 0] "./vim/bundle/closetag.vim",
[ 1] "./vim/bundle/ctrlp.vim",
...
[31] "./vim/bundle/vim-vividchalk",
[32] "./vim/bundle/Vundle.vim"
]
I can use an absolute path also:
Dir['/Users/ttm/vim/bundle/*']
And get:
[
[ 0] "/Users/ttm/vim/bundle/closetag.vim",
[ 1] "/Users/ttm/vim/bundle/ctrlp.vim",
...
[31] "/Users/ttm/vim/bundle/vim-vividchalk",
[32] "/Users/ttm/vim/bundle/Vundle.vim"
]
Notice that you get relative pathnames if you use a relative glob string, and absolute pathnames for an absolute glob string.
Upvotes: 2
Reputation: 4088
You need to use the entries method
Dir.entries('/')
=> [".", "..", ".apdisk", ".com.apple.backupd.mvlist.plist", ".dbfseventsd", ".DocumentRevisions-V100", ".DS_Store", ".file", ".fseventsd", ".hotfiles.btree", ".MobileBackups",".OSInstallMessages", ".PKInstallSandboxManager", ".Spotlight-V100", ".SymAVx86QSFile", ".Trashes", ".vol", "Applications", "bin", "cores", "dev", "etc", "home", "Library", "net", "Network", "opt", "private", "sbin", "System", "tmp", "Users", "usr", "var", "Volumes", "~"]
Here is the oficial documentation http://www.ruby-doc.org/core-2.1.2/Dir.html#method-c-entries
Upvotes: 0