Create a gist now

Instantly share code, notes, and snippets.

@mislav /
Created Aug 20, 2012

What would you like to do?
Shell function that's a shortcut interface to rbenv to quickly pick & switch between Ruby versions

rbenv is great, but switching between Ruby versions with it is kind of a pain since you have to specify full version names all the time. Example:

# change version in shell:
$ rbenv shell ree-1.8.7-2012.02
# run command:
$ RBENV_VERSION=jruby- rake something
# enable 1.9 mode:
$ RBENV_VERSION=rbx-2.0.0-dev RBXOPT=-X19 ruby -v

rb() is a shell function that fixes this.

$ rb ree
$ rb jr rake something
$ rb rbx 19 ruby -v

The short version specifier you give is matched against all available versions with grep, and the last match is picked. This means if you say "1.8", it will pick a 1.8.7 version over 1.8.6 if you have both installed. To make it explicit you want 1.8.6, simply say "1.8.6" or just "8.6".

# Shortcut interface to rbenv to quickly pick & switch between Ruby versions.
# Usage:
# rb <version> [19]
# rb <version> [19] <command>...
# rb
# A version specifier can be a partial string which will be matched against
# available versions and the last match will be picked. The optional "19"
# argument switches JRuby or Rubinius to 1.9 mode.
# When no arguments are given, the current ruby version in the shell is reset
# to default.
# Examples:
# rb 1.8
# rb ree
# rb rbx irb
# rb rbx 19 ruby -v
# rb jr 19 rake something
rb() {
if [[ $# -lt 1 ]]; then
rbenv shell --unset
# warning: potentially destructive to user's environment
unset RBXOPT
local ver="$(rbenv versions --bare | grep "$1" | tail -1)"
if [[ -z $ver ]]; then
echo "no ruby version match found" >&2
return 1
if [[ $1 == 19 ]]; then
local rbx_opt="RBXOPT=-X19"
local jrb_opt="JRUBY_OPTS=--1.9"
if [[ $# -gt 0 ]]; then
env RBENV_VERSION="$ver" $rbx_opt $jrb_opt "$@"
[[ -n $rbx_opt || -n $jrb_opt ]] && export $rbx_opt $jrb_opt
rbenv shell "$ver"
$ ruby -v
ruby 1.9.3p194
$ rbenv versions
* 1.9.3-p194 (set by /Users/mislav/.rbenv/version)
$ rb 1.8 ruby -v
ruby 1.8.7, Ruby Enterprise Edition 2012.02
$ rb rbx ruby -v
rubinius 2.0.0dev (1.8.7)
$ rb rbx 19 ruby -v
rubinius 2.0.0dev (1.9.3)
$ rb jr ruby -v
jruby (ruby-1.8.7-p357)
$ rb jr 19 ruby -v
jruby (ruby-1.9.2-p312)
# change rbenv version for current shell
$ rb rbx
$ ruby -v
rubinius 2.0.0dev (1.8.7)
# reset it to default version
$ rb
$ ruby -v
ruby 1.9.3p194

MBO commented Aug 20, 2012

cd ~/.rbenv/versions
ln -s rbx-1.2.4 rbx
rbenv shell rbx

mislav commented Aug 20, 2012

@MBO: nice. However, won't now rbenv version list more versions than you have?

MBO commented Aug 24, 2012

@mislav You're right, that's problem with how rbenv lists installed versions by just listing content of versions directory. Worth to mention. I haven't thought about it because I rarely list versions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment