Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to detect if a string is a file or directory

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.

like image 388
phor2 Avatar asked Dec 14 '25 12:12

phor2


1 Answers

Does it depend on the last character only? If yes, arg[-1] is enough

if arg[-1] == ?/
    puts "#{arg} is a directory"
end
like image 105
ZelluX Avatar answered Dec 17 '25 09:12

ZelluX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!