Can ruby lookup path to a binary like in bash or gnu makefile?
Makefile
which node
bash
user@host:~$ which node
Answer thanks Senthess
ruby
needs some code cleanup
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
usage
which 'fakebin', 'realbin', 'realbin2'
=> /full/path/realbin
=> /full/path/realbin2
Actually which returns one line for each. This returns an array rather than a string, maybe better, maybe not.
see answer below for which that checks single input
Yes. Something like this:
Explanation:
We access the variable
PATH, and we split it according to the platform separator (:for Unix systems,;for Windows ). This will yield an array of paths. We then search for the first having a file with name matching the one provided as an argument.EDIT: If you want the full path, here’s another way of implementing it:
EDIT2: updated original code to add executable check. You could implement it like this: