Implementation of 'which' in pure Ruby
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