Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active June 23, 2024 17:25
Show Gist options
  • Save havenwood/a07e51966eb65d85251ff067f0c44bd5 to your computer and use it in GitHub Desktop.
Save havenwood/a07e51966eb65d85251ff067f0c44bd5 to your computer and use it in GitHub Desktop.
A `which` command for Ruby
module FileUtils
# Returns the full path to an executable command if it exists in the PATH.
#
# FileUtils.which('ruby') # => "/usr/bin/ruby"
# FileUtils.which('matz') # => nil
#
# Keyword arguments:
#
# - <tt>env: 'PATH'</tt> - the PATH environment variable.
# - <tt>separator: File::PATH_SEPARATOR</tt> - the PATH separator.
#
def which(command, env: 'PATH', separator: File::PATH_SEPARATOR)
ENV.fetch(env) { return nil }
.split(separator)
.filter_map { |dir| Dir.exist?(dir) && File.join(dir, command) }
.find { |path| File.file?(path) && File.executable?(path) }
end
module_function :which
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment