Duke Yu
Duke Yu

Reputation: 105

how can I know which Ruby executable was used in ruby script?

there are two Ruby environments on a system, normal ruby and Chef embedded ruby. I want to know, in a ruby script, which ruby executable is used to invoke the script itself. How can get that?

Upvotes: 1

Views: 216

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Recommended Solutions

Use the poorly-documented RbConfig module, if available:

RbConfig.ruby
#=> "/Users/foo/.rubies/ruby-2.7.0/bin/ruby"

Alternatively, you can use the easier-to-find Gem module from the standard library to do the same thing:

Gem.ruby
#=> "/Users/foo/.rubies/ruby-2.7.0/bin/ruby"

Other Approaches

The RbConfig and Gem modules are your best bet, but there may be times when you need to get at the version or path information another way. Here are some different approaches.

Get the Version

You can return the version of the executing Ruby as a String with:

RUBY_VERSION
#=> "2.7.0"

Get the Path

Ruby is usually installed to bin/ruby in the RUBY_ROOT. You can return the expected path to the running Ruby binary (and verify it actually exists, if necessary) as follows:

ENV["RUBY_ROOT"] + "/bin/ruby"
#=> "/Users/foo/.rubies/ruby-2.7.0/bin/ruby"

File.exist? ENV["RUBY_ROOT"] + "/bin/ruby"
#=> true

Alternatively, you can use Kernel#` to find the first Ruby in your PATH as follows:

`which ruby`.chomp
=> "/Users/foo/.rubies/ruby-2.7.0/bin/ruby"

There are certainly edge cases where either approach can be misleading, though. For example, Ruby may have been built in a non-standard way, or you may have invoked Ruby with a fully-qualified path rather than calling the first binary in PATH. That makes "roll your own" lookups less reliable, but if your environment is missing the RbConfig or Gem modules for some reason, this might be a reasonable alternative for you.

Upvotes: 3

Related Questions