DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Implementation Of 'which' In Pure Ruby

04.09.2006
| 2328 views |
  • submit to reddit
        Written by someone called 'erikh' on #rubyonrails on irc.freenode.net.

module Which
 
  #
  # 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.
  #
  # Those familiar with the which(1) utility from UNIX will notice the
  # similarities.
  #
 
  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
 
  module_function :which
end