An easy way to determine if a string is a file or directory

I am trying to write a small ruby ​​script that determines whether a given argument is a file or directory based on a string containing trailing /or not.

To be clear, I'm not interested in knowing if a file or directory exists, in other words, AFAIK File.directory?will not work for me.

Also, all the methods that I found in the standard library, for example Pathname.basename, automatically delete the trailing one /(if any). So, let's do something like this:

arg = "/foo/bar/baz/"
if File.basename(arg).include?("/")
    puts "#{arg} is a directory"
end

does not work.

Is there a concise way to do this? Did I miss something?

I would prefer not to resort to regular expression, if at all possible.

+3
3

? , arg[-1]

if arg[-1] == ?/
    puts "#{arg} is a directory"
end
+8

/foo/bar/baz baz /foo/bar, /foo/bar/baz, , .

- * nix - . , , -, :

is_directory = arg =~ %r{#{File.PATH_SEPARATOR}\Z}

is_directory = arg[=1] == File.PATH_SEPARATOR
+2

Do you mean something like this?

puts "#{arg} is a directory" if arg =~ %r|/\z|
0
source

All Articles