Separator in $PATH

S

Stefano Mioli

Hello everyone,
Unix-like operating systems use a colon to separate each directory in
the PATH, while Windows uses a semicolon.

The question is: is there some class in the Ruby library that knows
about this difference?
Or do I have to resort to something like the following?

if RUBY_PLATFORM =~ /(win|w)32$/
# ...
end

I'm asking this question because I need to figure out if a given
executable is in the path and, if it does, retrieve its full path.
So I whipped up this one-liner which seems to work as expected (except
on Windows, of course):

ENV["PATH"].split(":").collect {|p| File.join(p, "foo")}.keep_if{|p|
File.exist? p}.first

where "foo" is the name of the executable.
While we're at it, can someone think of a better / more idiomatic way to
do it?

Obviously, simply trying to run the executable is not an option.

Thanks in advance.
 
D

Daniel Berger

Hello everyone,
=A0 =A0 =A0 =A0 Unix-like operating systems use a colon to separate each = directory in
the PATH, while Windows uses a semicolon.

The question is: is there some class in the Ruby library that knows
about this difference?
File::pATH_SEPARATOR

I'm asking this question because I need to figure out if a given
executable is in the path and, if it does, retrieve its full path.

require 'ptools'

File.which('ls') # =3D> '/bin/ls'

Works on Windows, too, with or without an extension:

File.which('notepad') # Works
File.which('notepad.exe') # Also works

Regards,

Dan
 
S

Stefano Mioli

require 'ptools'

File.which('ls') # =3D> '/bin/ls'

Works on Windows, too, with or without an extension:

File.which('notepad') =A0 =A0 # Works
File.which('notepad.exe') # Also works

Many thanks, Dan.
I didn't know about ptools, and somehow I just saw File::SEPARATOR,
but not File::pATH_SEPARATOR.

--=20
Stefano
 
R

Robert Klemme

string#split accept a regular expression

path_list = ENV['PATH'].split(/[:;]/) # work s on Linus and Windows

HTH gfb

Well, it works. But it isn't helpful.

irb(main):002:0> 'C:\\foo;W::\\bar'.split(/[:;]/)
=> ["C", "\\foo", "W", "", "\\bar"]

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top