Ruby 相当于 'which'

标签 ruby

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/

相关文章:

ruby-on-rails - ruby open ssl api for encrypted key (without nodes option)

ruby-on-rails - 如何在 Rails 3.1 中复制 class_inheritable_accessor 的行为?

ruby - 数组中没有内存错误#max

sql - 从字符串中删除前 4 个字符

ruby-on-rails - 如何链接 allow_any_instance_of 与 Rspec

ruby - Ruby 中的 Kernel#select 有什么意义?

ruby-on-rails - 当您可以使用常规 Ruby 类方法时,为什么要使用作用域?

ruby-on-rails - 如何在保存一个模型之前更新另一个模型的数据

ruby-on-rails - 我怎样才能让 bundler 不提示 sys-proctable gem?

Ruby:对选定的哈希值求和