Last active
June 23, 2024 17:25
-
-
Save havenwood/a07e51966eb65d85251ff067f0c44bd5 to your computer and use it in GitHub Desktop.
A `which` command for Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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