Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active October 24, 2024 19:12
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
# frozen_string_literal: true
require 'fileutils'
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) { break }.split(separator).each do |dir|
next unless Dir.exist?(dir)
path = File.join(dir, command)
next unless File.file?(path) && File.executable?(path)
return path
end
nil
end
module_function :which
end
path = FileUtils.which(ARGV.unshift)
abort unless path
puts path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment