9

I have an Array of Strings and I want to select only these Strings which are paths to files:

My path is "~/dlds/some_file.ics" where ~/dlds is a symlink to ~/archive/downloads on my system. The file has following permissions:

-rw-r--r--

My code (I tried several variants):

ARGV.select do |string|
    File.file? string # returns false
    Pathname.new(string).file? # returns false
    Pathname.new(string).expand_path.file? # returns false
end

I don't know what else to try.

I'm running Ruby 2.2.0 or 2.2.2.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
musicmatze
  • 4,124
  • 7
  • 33
  • 48

3 Answers3

17
File.exist? File.expand_path "~/dlds/some_file.ics"
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • 3
    note this returns true if the path is also a directory. details here: http://stackoverflow.com/questions/8590098/ruby-function-to-check-file-existence – Crashalot Apr 21 '16 at 08:43
1

Your question is a bit confusing. If you want to check if the file exists, you should just do as you did:

Pathname.new(file_name).file? 

If you are using the ~ you will first have to expand the path, so write:

Pathname.new(file_name).expand_path.file? 

If you want to check if the given file_name is a symlink, you can just do

Pathname.new(file_name).expand_path.symlink? 

If you want to find the file the symlink points to, you have to follow the link:

File.readlink(Pathname.new(file_name).expand_path) 

which will return the filename of the linked file, so if you really wanted you could do something like:

Pathname.new(File.readlink(Pathname.new(file_name).expand_path)).file? 

to make sure the symlink is pointing to an existing file.

nathanvda
  • 49,707
  • 13
  • 117
  • 139
0

I think File.readlink is what you are looking for

Returns the name of the file referenced by the given link. Not available on all platforms.

File.readlink("path/to/symlink")
Arsen
  • 10,815
  • 2
  • 34
  • 46