Last Updated: February 25, 2016
· srigi

Display actual Ruby version & gemset in prompt

When working in console, I want to know which Ruby and gemset is currently activated by RVM. Best solution is to display this information in prompt:


RVM provide function for that purpose - just put rvm-prompt into command-line:

→ rvm-prompt
→ rvm use 1.9.3
→ rvm-prompt

When on default gemset, this is not in output of rvm-prompt. Also that ruby- prefix is not needed for our needs.

Lets store output into variable:

→ rbv=`rvm-prompt`

Of course echoing that variable will yield same result:

→ echo $rbv

Let's modify evaluation of that variable bit. In bash (or zsh) you can utilize so called parameter expansion. Best to illustrate is put some example output:

→ echo ${#rbv}

Output of this command is string length stored in rbv. Let's try another:

→ echo ${rbv:5}

This put to console substring stored in rbv starting from 6th char till end of string. Now we start getting somewhere. But let's be little bit smarter:

→ echo ${rbv#ruby-}

This expansion return string without matching pattern in front of the string.

OK, but how about that default gemset? Well, we will go brute-force :) If there is not a @ character in rvm-prompt's output, we will concatenate our little variable with @default. Not very smart, but works well in our scenario.

How to test if there is a particular character in string?

→ [[ $rbv == *"@"* ]]
→ echo $?

We are testing presence of @ in rbv. Result is stored in exit code of interpreter. That funny echo will put exit code of last command to the console. In this case @ is not present. In oposite case 0 would be returned.

Now it is time to glue it all together. Create function in your .bash_profile or .zshrc in your home folder:

function prompt_rvm {
    [[ $rbv == *"@"* ]] || rbv="${rbv}@default"
    echo $rbv

And consume that function in your prompt later

bash: export PS1="\u@\h \w \$(prompt_rvm) \$ "

zsh: PROMPT='%n@%m %~ $(prompt_rvm)

cheers :)