18

Inside a ruby script, how do I get the path to the ruby interpreter?

Example script:

  #!/path/to/ruby
  puts `#{RUBY_INTERPRETER_PATH} -e "puts 'hi'"`
  #EOF

Where RUBY_INTERPRETER_PATH is a mythical way of finding /path/to/ruby.

This is just an example, though. I realize in this case that I could just copy /path/to/ruby into the script, but I don't want to do that. I want this to work "correctly" regardless of what the #! line says. Even if running under windows.

Ciao!

docwhat
  • 11,435
  • 6
  • 55
  • 54

2 Answers2

20

These days (1.9+) you can use built-in methods (which are supposed to work with Jruby, etc.) like this:

RbConfig.ruby or Gem.ruby

$ irb --simple-prompt
>> RbConfig.ruby
=> "C:/installs/Ruby193/bin/ruby.exe"
>> Gem.ruby
=> "C:/installs/Ruby193/bin/ruby.exe"
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
  • I can confirm it works for jruby: `ruby -e 'puts RbConfig.ruby' => /usr/local/var/rbenv/versions/jruby-1.7.4/bin/jruby` – docwhat Jul 20 '13 at 21:05
  • 1
    Even on 1.8, you could `require "rubygems"; puts(Gem.ruby())`. Would it be guaranteed correct, per @user945466, if someone had installed such a binary elsewhere? On Linux you could get a guaranteed answer with `puts(File.readlink("/proc/self/exe"))`. – Martin Dorey Aug 25 '17 at 18:05
15

To get the path of the currently running ruby interpreter:

require 'rbconfig'
RUBY_INTERPRETER_PATH = File.join(RbConfig::CONFIG["bindir"],
                                  RbConfig::CONFIG["RUBY_INSTALL_NAME"] +
                                  RbConfig::CONFIG["EXEEXT"])
michaelrp
  • 663
  • 4
  • 9
mckeed
  • 9,719
  • 2
  • 37
  • 41
  • 1
    I keep forgetting about `rbconfig`; It's so useful. – docwhat Aug 11 '11 at 23:30
  • 1
    While the answer using 'rbconfig' is very useful for finding the path to an installed Ruby interpreter, it DOES NOT GUARANTEE that THIS process is actually an instance of that interpreter running. It could be a totally different executable residing elsewhere on the system. –  Sep 14 '11 at 20:20
  • This works great on rbx 3.65, jruby 9.1.6.0 and mri 1.8.7-2.3.3 on mac and linux. Untested on windows or anything else. –  Nov 28 '16 at 22:51