gpt4 book ai didi

Ruby 相当于 'which'

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:00 24 4
gpt4 key购买 nike

ruby 可以像 bash 或 gnu makefile 一样查找二进制文件的路径吗?

生成文件

which node

庆典

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com