module Which

Skeleton module for the 'which' routine.

Ideally, one would do this in their code to import the “which” call directly into their current namespace:

require 'which'
include Which
# do something with which()

It is recommended that you look at the documentation for the which() call directly for specific usage.

Public Class Methods

which(filename, path=ENV["PATH"], path_sep=File::PATH_SEPARATOR, dir_sep=File::SEPARATOR) click to toggle source

Searches the path, or a provided path with given separators (path_sep, commonly “:”) and a separator for directories (dir_sep, commonly “/” or “\” on windows), will return all of the places that filename occurs. `filename' is included as a part of the output.

Note that the filename must both exist in the path and be executable for it to appear in the return value.

Those familiar with the which(1) utility from UNIX will notice the similarities.

# File lib/fixwhich.rb, line 64
def which(filename, path=ENV["PATH"], path_sep=File::PATH_SEPARATOR, dir_sep=File::SEPARATOR)
  dirs = path.split(/#{path_sep}/)

  locations = []

  dirs.each do |dir|
    newfile = "#{dir}#{dir_sep}#{filename}"
    # strip any extra dir separators
    newfile.gsub!(/#{dir_sep}{2,}/, "#{dir_sep}")
    p = Pathname.new(newfile)
    if p.exist? and p.executable?
      locations.push(newfile)
    end
  end

  return locations
end

Private Instance Methods

which(filename, path=ENV["PATH"], path_sep=File::PATH_SEPARATOR, dir_sep=File::SEPARATOR) click to toggle source

Searches the path, or a provided path with given separators (path_sep, commonly “:”) and a separator for directories (dir_sep, commonly “/” or “\” on windows), will return all of the places that filename occurs. `filename' is included as a part of the output.

Note that the filename must both exist in the path and be executable for it to appear in the return value.

Those familiar with the which(1) utility from UNIX will notice the similarities.

# File lib/fixwhich.rb, line 64
def which(filename, path=ENV["PATH"], path_sep=File::PATH_SEPARATOR, dir_sep=File::SEPARATOR)
  dirs = path.split(/#{path_sep}/)

  locations = []

  dirs.each do |dir|
    newfile = "#{dir}#{dir_sep}#{filename}"
    # strip any extra dir separators
    newfile.gsub!(/#{dir_sep}{2,}/, "#{dir_sep}")
    p = Pathname.new(newfile)
    if p.exist? and p.executable?
      locations.push(newfile)
    end
  end

  return locations
end