How to use specify version of ruby for shell script with rbenv

ruby

I'm going to write some short script in ruby.
And I want to specify ruby version by shebang or in another way.

I'll use the script in many environments.
I'm using rbenv in the evironments, but it's not sure which version of ruby is installed.

The script must fail if the specify version of ruby is not installed.

How can I do it? Is there good way that I should follow?

Best Answer

According to the official docs it sounds like you just need to prefix your scripts like this:

#!/usr/bin/env ruby

And then do one of the following things to tell rbenv which version of Ruby to use:

excerpt: https://github.com/sstephenson/rbenv

Choosing the Ruby Version

When you execute a shim, rbenv determines which Ruby version to use by reading it from the following sources, in this order:

  1. The RBENV_VERSION environment variable, if specified. You can use the rbenv shell command to set this environment variable in your current shell session.

  2. The first .ruby-version file found by searching the directory of the script you are executing and each of its parent directories until reaching the root of your filesystem.

  3. The first .ruby-version file found by searching the current working directory and each of its parent directories until reaching the root of your filesystem. You can modify the .ruby-version file in the current working directory with the rbenv local command.

  4. The global ~/.rbenv/version file. You can modify this file using the rbenv global command. If the global version file is not present, rbenv assumes you want to use the "system" Ruby—i.e. whatever version would be run if rbenv weren't in your path.

You can then use this command to create a .ruby-version file in the directory along with the Ruby script.

$ rbenv local 1.9.3-p327
Related Question