tags:

views:

154

answers:

2

In python, you can do

>>> import sys
>>> sys.executable
'/usr/bin/python'

to get at the executable's location. Can you do the same thing just using something built-in to ruby? It can be a special variable, method, etc.

If there isn't, what is the cleanest, most reliable way of determining the ruby executable's location in a cross-platform way?

Related:

+1  A: 

Works in a script, not from irb:

puts open($PROGRAM_NAME).readline.gsub /#! *([^ ]+).*/, '\1'

;-)

andre-r
That doesn't work if the first line of my program is "#!/usr/bin/env ruby"...
Arthur Reutenauer
I know, also env isn't the interpreter. It is not supposed to be very serious anyway.
andre-r
I got that from the smiley ;-) Is there really no internal variable that tells us the path of the executable being run? I had a quick look at my Ruby cookbook but couldn't find anything.
Arthur Reutenauer
+2  A: 

Linux-based systems are OK with

`whereis ruby`.split(" ")[1]

It will call whereis ruby and parse its' output for the second entry (first contains 'whereis:')

The more strict method is to call

puts `ls -al /proc/#{$$}/exe`.split(" ")[-1]

It will get the executable name for the current process (there is $$ variable and Process.pid method to obtain that) from /proc/pid/exe symlink information.

kirushik
Or just `\`which ruby\``, and good idea with /proc/pid/exe.
andre-r
+1 to /proc/pid/exe. However I guess we have to craft a special cross-platform glue method to answer this question. I hope someone (matz?) would come out and say it right out that "There's no such thing built-in to ruby".
ento