rbenv: Install and Set a Local Ruby in CI
rbenv install <version> compiles Ruby with ruby-build, and rbenv local <version> writes .ruby-version so shims select it for the project.
rbenv manages Ruby versions through shims, much like pyenv does for Python. It compiles Ruby from source, so CI needs the build dependencies, and the shims need the init eval to be on PATH.
What it does
rbenv intercepts ruby, gem, and bundle via shims and dispatches them to the version chosen by .ruby-version (local), the global setting, or RBENV_VERSION. rbenv install uses the ruby-build plugin to compile and install a version.
Common usage
# build deps (Ubuntu)
sudo apt-get install -y autoconf patch build-essential libssl-dev \
libyaml-dev libreadline-dev zlib1g-dev libgmp-dev libffi-dev
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
rbenv install 3.3.1
rbenv local 3.3.1 # writes .ruby-version
ruby -vOptions
| Command / flag | What it does |
|---|---|
| rbenv install <v> | Compile and install a Ruby (needs ruby-build) |
| rbenv install -s <v> | Skip if already installed |
| rbenv local <v> | Write .ruby-version for this directory |
| rbenv global <v> | Set the default Ruby |
| rbenv rehash | Regenerate shims after installing gems with binaries |
| eval "$(rbenv init -)" | Add shims to PATH |
In CI
Run eval "$(rbenv init -)" in each step. After gem install of a gem that ships an executable (e.g. rails), run rbenv rehash or the new shim is missing. Cache ~/.rbenv/versions to avoid recompiling Ruby each run.
Common errors in CI
"rbenv: ruby: command not found" means init was not eval'd (shims off PATH) or a rehash is needed. "Your Ruby version is X, but your Gemfile specified Y" means .ruby-version and the Gemfile disagree. "The Ruby openssl extension was not compiled" means libssl-dev was missing during rbenv install. "version `3.3.1' is not installed" means the pin points at an uninstalled Ruby.