Ruby 可以像 bash 或 gnu makefile 一样查找二进制文件的路径吗?
生成文件
which node
bash
user@host:~$ which node
谢谢Senthess的回答
ruby
需要一些代码清理
def which(*args)
ret = []
args.each{ |bin|
possibles = ENV["PATH"].split( File::PATH_SEPARATOR )
possibles.map {|p| File.join( p, bin ) }.find {|p| ret.push p if File.executable?(p) }
}
ret
end
使用
which 'fakebin', 'realbin', 'realbin2'
=> /full/path/realbin
=> /full/path/realbin2
实际上,每个返回一行。这返回一个数组而不是一个字符串,也许更好,也许不是。
请参阅下面的答案,了解检查 single input 的
最佳答案
是的。像这样的事情:
def which(binary)
ENV["PATH"].split(File::PATH_SEPARATOR).find {|p| File.exists?( File.join( p, binary ) ) }
end
说明:
我们访问变量PATH
,并根据平台分隔符(对于Unix系统为:
,对于Windows系统为;
)来分割它。这将产生一系列路径。然后,我们搜索第一个文件名与作为参数提供的文件名匹配的文件。
编辑:如果您想要完整路径,这是实现它的另一种方法:
def which(binary)
possibles = ENV["PATH"].split(File::PATH_SEPARATOR)
possibles.map {|p| File.join( p, binary ) }.find {|p| File.exists?(p) && File.executable?(p) }
end
EDIT2:更新了原始代码以添加可执行检查。你可以这样实现:
def which_multiple(*args)
args.map {|e| which(e)}
end
关于Ruby 相当于 'which',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6624348/