Search code examples
rubyversionruby-2.7

How to use a specific Ruby version in a simple non-Rails project


I'd like to use Ruby 2.7.1 in my simple non-Rails project. I start my main file with the comment:

#!/usr/bin/ruby

I installed Ruby 2.7.1 via RVM and it is set properly:

$ rvm list
   ruby-2.6.1 [ x86_64 ]
=* ruby-2.7.1 [ x86_64 ]

When I run my program it uses Ruby 2.6.1.

In /usr/bin/ I have only ruby and ruby2.5 files.

How can I force my program to use Ruby 2.7.1 or simply the version RVM calls currently and its default?

I use Ubuntu 18.04.


Solution

  • Use this at the top of your script:

    #!/usr/bin/env ruby
    

    This will cause the script to check the environment of the user running the utility to find the appropriate Ruby interpreter. From the Wikipedia page on env:

    env is a shell command for Unix and Unix-like operating systems. It is used to either print a list of environment variables or run another utility in an altered environment without having to modify the currently existing environment. Using env, variables may be added or removed, and existing variables may be changed by assigning new values to them.

    In practice, env has another common use. It is often used by shell scripts to launch the correct interpreter. In this usage, the environment is typically not changed.

    That means you can use this for any type of interpreter, like perl, python, sh, etc.