Reputation: 637
I'm trying to write a small ruby script that detects if a given argument is a file or a directory, based on the string containing a trailing /
or not.
To be clear I'm not interested to know if the file or directory actually exists, in other words AFAIK File.directory?
will not work for me.
Also all the methods I found in the standard library, such as Pathname.basename
automatically remove the trailing /
(if any). So doing something like this:
arg = "/foo/bar/baz/"
if File.basename(arg).include?("/")
puts "#{arg} is a directory"
end
would not work.
Is there a concise way of doing this? Am I missing something?
I would rather not resort to regex if at all possible.
Upvotes: 3
Views: 1934
Reputation: 32367
Since /foo/bar/baz
can refer to either a file named baz
in the /foo/bar
directory or a directory named /foo/bar/baz
there is no way to deterministically establish if it is a directory or a file without actually hitting the file system.
The rules for file names do not make a distinction between files and directories - in fact in many flavors of *nix a directory is a file just with special attributes. If you want to establish a rule for your application that states that directories will always end in a trailing separator then you can use:
is_directory = arg =~ %r{#{File.PATH_SEPARATOR}\Z}
or
is_directory = arg[=1] == File.PATH_SEPARATOR
Upvotes: 2
Reputation: 168101
You mean something like this?
puts "#{arg} is a directory" if arg =~ %r|/\z|
Upvotes: 0
Reputation: 72655
Does it depend on the last character only? If yes, arg[-1]
is enough
if arg[-1] == ?/
puts "#{arg} is a directory"
end
Upvotes: 8