Ruby相当于'哪个'

Dre*_*rew 2 ruby

ruby可以在bash或gnu makefile中查找二进制文件的路径吗?

Makefile文件

which node
Run Code Online (Sandbox Code Playgroud)

庆典

user@host:~$ which node
Run Code Online (Sandbox Code Playgroud)

回答谢谢Senthess

红宝石

需要一些代码清理

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
Run Code Online (Sandbox Code Playgroud)

用法

which 'fakebin', 'realbin', 'realbin2'
=> /full/path/realbin
=> /full/path/realbin2
Run Code Online (Sandbox Code Playgroud)

实际上每个返回一行.这会返回一个数组而不是一个字符串,也许更好,也许不是.

见下文回答,检查单输入

Sen*_*ess 6

是.像这样的东西:

def which(binary)
   ENV["PATH"].split(File::PATH_SEPARATOR).find {|p| File.exists?( File.join( p, binary ) ) }
end
Run Code Online (Sandbox Code Playgroud)

说明:

我们访问变量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
Run Code Online (Sandbox Code Playgroud)

EDIT2:更新原始代码以添加可执行检查.你可以像这样实现它:

def which_multiple(*args)
    args.map {|e| which(e)}
end
Run Code Online (Sandbox Code Playgroud)