0

I have an image with the filename media_httpfarm3static_mAyIi.jpg.

I would like to search the parent folder and all subfolders of that parent folder for a file that contains that name - it doesn't have to be the EXACT name, but must contain that string.

E.g. this file should be returned: 11605730-media_httpfarm3static_mAyIi.jpg

So this is a 2-part question:

  1. How do I achieve the above?
  2. Once I have the file, how do I return the path for that file?
4

1 回答 1

4

Use Dir::[] and File::absolute_path:

partial_name = "media_httpfarm3static_mAyIi.jpg"
Dir["../**/*#{partial_name}"].each do |filename|
  puts File.absolute_path(filename)
end

This uses the glob "../**/*media_httpfarm3static_mAyIi.jpg" (go up one directory, then search all sub directories (recursively), for any file ending in the partial string "media_httpfarm3static_mAyIi.jpg". The relative paths are then returned in an Array.

You can use Array#each, Array#map, etc. to convert this into what you need. To convert a relative path, into an absolute path, just pass it to File::absolute_path.

Once you have the absolute path, you can use it to open the file, read the file, etc.

On File Paths

The glob "../**/*media_httpfarm3static_mAyIi.jpg" is relative to the current working directory. Normally, this is the directory from which the program was run. Not the directory of the source file. This can change using various utilities to change it.

To always use a glob relative to the source code file, try:

Dir[File.expand_path('../**/*#{partial_name}', __FILE__)]

You can also use:

Dir[File.join(__dir__, "..", "**", "*#{partial_name}")]

Note: __dir__ was added in Ruby 2.0. For older versions of ruby use File.dirname(__FILE__)

In the first code sample File::absolute_path was used. In the last sample File::expand_path is used. In most situations these can be used interchangeably. There is a minor difference, per the documentations:

File::absolute_path

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. If the given pathname starts with a “~” it is NOT expanded, it is treated as a normal directory name.

File::expand_path

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~user” expands to the named user’s home directory.

于 2013-04-30T16:04:36.670 回答