Reputation: 118289
I have tried the following which helped me to see the 1-level down directory path
:
E:\WIPData\Ruby\Scripts>irb
irb(main):001:0> Dir.pwd
=> "E:/WIPData/Ruby/Scripts"
irb(main):004:0> Dir.pwd.gsub(/\/Scripts/,'')
=> "E:/WIPData/Ruby"
irb(main):005:0>
Is there a way to get the the directory full path
1-level up and 1-level down, from the current directory without changing it?
File structure
=================
Dir-> E:\WIPData\
|
(E:\WIPData\Ruby)
|
--------------------------------------------------
| | | | |
(xxx) (yyyy) (zzzz) (pppp) (E:\WIPData\Ruby\Scripts) <= It is PWD
Upvotes: 1
Views: 1948
Reputation: 160571
To get the parent directory from a path, use:
File.dirname('/path/to/a/file.txt')
=> "/path/to/a"
There isn't a way to get "the" child directory, unless there is only one, because file systems don't have a concept of a default sub-directory. If there is only one, it's an obvious choice to you, but not to your code. To get a list of the sub-directories only:
Dir.entries('.').select{ |e| File.directory?(e) }
That will return the child directories under '.'
(AKA the current directory) as an array, which will be ['.', '..']
at a minimum, meaning the current and parent directories respectively. For instance, in the current directory my pry instance is running in, I get back:
[".", "..", ".svn", "old"]
as the list of available directories. Which is the default? I could do this:
Dir.entries('.').select{ |e| File.directory?(e) && !e[/^\./] }
=> ["old"]
which returns the only "visible" directory, i.e., it isn't a "hidden" directory because it doesn't start with '.'
. That isn't the default, because, as I said, the file system has no "default" child directory concept. In another directory I'd probably see many directories returned, so I'd have to specify which to descend into, or use for file access.
Ruby has a nice suite of File and Dir tools, plus the Find class, so read through their documentation to see what you can do.
Upvotes: 1
Reputation: 2796
you can find first subDirectory in your current directory this way:
Dir.glob('*').find { |fn| File.directory?(fn) }
allthough, it's not uniquely defined, as someone said.
and first parent directory this way:
File.expand_path("..", Dir.pwd)
HTH
Upvotes: 2