Ruby相当于'哪个'

时间:2011-07-08 12:23:40

标签: ruby

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

生成文件

which node

的bash

user@host:~$ which node

回答感谢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

使用

which 'fakebin', 'realbin', 'realbin2'
=> /full/path/realbin
=> /full/path/realbin2

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

请参阅下面的答案,了解哪个检查single input

1 个答案:

答案 0 :(得分:6)

是。像这样:

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