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:
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.
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.