Over a million developers have joined DZone.

Implementation Of 'which' In Pure Ruby

·
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
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}