“which in ruby”: Checking if program exists in $PATH from ruby

后端 未结 16 1084
萌比男神i
萌比男神i 2020-12-07 12:15

my scripts rely heavily on external programs and scripts. I need to be sure that a program I need to call exists. Manually, I\'d check this using \'which\' in the commandlin

16条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 12:35

    This is a tweak of rogeriopvl's answer, making it cross platform:

    require 'rbconfig'
    
    def is_windows?
      Config::CONFIG["host_os"] =~ /mswin|mingw/
    end
    
    def exists_in_path?(file)
      entries = ENV['PATH'].split(is_windows? ? ";" : ":")
      entries.any? {|f| File.exists?("#{f}/#{file}")}
    end
    

提交回复
热议问题