rsk82
rsk82

Reputation: 29377

how to get path to ruby.exe that is running current script on windows?

There are variables in other scripts like:

python: print(sys.executable)

php: echo PHP_BINARY."\n";

is there anything like that in ruby ?

(ruby v.2.0)

Upvotes: 2

Views: 1729

Answers (3)

Peter Vrabel
Peter Vrabel

Reputation: 372

None of the answers below work reliably. They use static information but your ruby script might be executed by a ruby instance installed in a different than default path or in a path which is not in the PATH environment variable.

What you need to do is to use WIN32 api. In particular, GetModuleHandle and GetModuleFileName functions need to be called. The first one gets a handle of actual process, the other one returns its path.

Example for inspiration:

require 'ffi'

module Helpers
  extend FFI::Library

  ffi_lib :kernel32

  typedef :uintptr_t, :hmodule
  typedef :ulong, :dword

  attach_function :GetModuleHandle, :GetModuleHandleA, [:string], :hmodule
  attach_function :GetModuleFileName, :GetModuleFileNameA, [:hmodule, :pointer, :dword], :dword

  def self.actualRubyExecutable
    processHandle = GetModuleHandle nil

    # There is a potential issue if the ruby executable path is
    # longer than 999 chars.
    rubyPath = FFI::MemoryPointer.new 1000
    rubyPathSize = GetModuleFileName processHandle, rubyPath, 999

    rubyPath.read_string rubyPathSize
  end
end

puts Helpers.actualRubyExecutable

On Linux, this information can be read from /proc directory.

Upvotes: 1

Lifeweaver
Lifeweaver

Reputation: 1042

Try %x(where ruby) you must have the ruby.exe in your path for this to work so windows knows what 'ruby' your talking about.

Upvotes: 0

lifus
lifus

Reputation: 8482

You may take a look at rubinius configure(build_ruby)

So, currently it looks as follows:

require 'rbconfig'

def build_ruby
  unless @build_ruby
    bin = RbConfig::CONFIG["RUBY_INSTALL_NAME"] || RbConfig::CONFIG["ruby_install_name"]
    bin += (RbConfig::CONFIG['EXEEXT'] || RbConfig::CONFIG['exeext'] || '')
    @build_ruby = File.join(RbConfig::CONFIG['bindir'], bin)
  end
  @build_ruby
end

I also tried the following:

require 'rbconfig'

File.join( RbConfig::CONFIG['bindir'],
           RbConfig::CONFIG['RUBY_INSTALL_NAME'] + RbConfig::CONFIG['EXEEXT']
         )

It works for me just as good.

Upvotes: 0

Related Questions