Run commands using a different ruby version using rbenv

While building a script to test ruby version upgrades in a rbenv-enabled system, I noticed that running bundle install from within a ruby script uses the script’s version of ruby instead of the one defined in the directory.

Tags : Ruby rbenv

Published: August 27, 2023

In particular, bundle install failed with the infamous Your Ruby version is 3.1.2, but your Gemfile specified 3.1.3.

I tested several ideas that didn’t work:

  • running rbenv rehash, separately or from the same system call
  • setting RBENV_VERSION and/or RUBY_VERSION while executing the command: system({"RBENV_VERSION" => X.Y.Z}, command)
  • setting RBENV_VERSION and/or RUBY_VERSION before launching the new command

What finally worked, with the minimum impact, was to prepend the PATH with rbenv’s target version executable before running bundle install.

version = "3.1.3"
`rbenv local #{version}`

# Force rbenv to use the new version
ENV["PATH"] = "#{ENV["HOME"]}/.rbenv/versions/#{version}/bin:#{ENV["PATH"]}"

# run scripts, for instance:
`bundle install`

# Reset PATH
ENV["PATH"] = ENV["PATH"].split(":")[1..].join(":")

Side-note: we can’t use prepend to change ENV["PATH"] because it is frozen.

Previous page Previous page Next page Next page