What is the Ruby Python equivalent of sys.executable?

In Python, you can do

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

      

to get into the executable. Can you do the same just using something built in for Ruby? It can be a special variable, method, etc.

If not, what's the cleanest and most reliable way to determine the ruby ​​executable location in a cross-platform way?

Similar

+2


source to share


5 answers


Run this in IRB:

require 'rbconfig'

key_length = RbConfig::CONFIG.keys.max{ |a,b| a.length <=> b.length }.length
RbConfig::CONFIG.keys.sort_by{ |a| a.downcase }.each { |k| puts "%*s => %s" % [key_length, k, RbConfig::CONFIG[k]] }

      

It will list the awesome print styles of all Ruby configuration information.

   ALLOCA => 
       AR => ar
     arch => x86_64-darwin10.5.0
ARCH_FLAG => 
  archdir => /Users/greg/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/x86_64-darwin10.5.0
 ARCHFILE => 
       AS => as
  ASFLAGS => 
 BASERUBY => ruby
   bindir => /Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin

      

bindir

is the path to the current Ruby interpreter. Above him on the list BASERUBY => ruby

.



RbConfig::CONFIG.values_at('bindir', 'BASERUBY').join('/')
=> "/Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/ruby"

      

Checking my work:

greg-mbp-wireless:~ greg$ which ruby
/Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/ruby

      

There's a lot more information out there than that, so it's worth running the code I added above to see what's available.

+6


source


Linux systems are fine with

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

      

It will call whereis ruby

and parse its' output for the second entry (contains' whereis: 'first)



A stricter method is to call

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

      

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

+2


source


Works in a script, not from irb

:

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

      

; -)

+1


source


Seems like the answer in RbConfig :: CONFIG I think RbConfig :: CONFIG ['bindir'] provides the directory where the executable is located, the rest is s (or should be) straight.

RbConfig :: CONFIG ['bindir'] + '/ ruby' should work even on windows as exe might be skipped

+1


source


It looks like the only reliable way is

 system("#{Gem.ruby} another_file.rb")

      

This even works for odd cases like jruby that run like jars, etc.

Also see

 OS.ruby_bin

      

https://github.com/rdp/os

+1


source







All Articles