2020-05-14:
Shebang That Picks From Multiple Possible Ruby Interpreters

Problem

On my home machine I have ruby 2.5 in /usr/bin/ruby. At work, /usr/bin/ruby is an ancient 1.8.7, and the modern rubies (v2+) are in a strange tools path that looks like this:

/home/tools/installs/ruby-2.4.0/bin/ruby

But I have scripts that I want to work on both systems, without having to update the shebang line everytime I make changes.

I also can't install rbenv or rvm at work, which leaves me with...

The Solution

Based on the polyglot I created to call rails scripts with args I've created a new Bash/Ruby polyglot that can check for the existence of ruby executables to figure out which one to run:
#!/bin/sh
# vi: set syntax=ruby:
##################################################
# polyglot to use shell to pick correct ruby
##################################################
if [ "a" != "a" ]; then
  printf "" # polyglot 'nop' - we are in ruby
=begin
else
  if [ -x "/home/tools/installs/ruby-2.4.0/bin/ruby" ]; then
    set "/home/tools/installs/ruby-2.4.0/bin/ruby" "$0" "$*"
  else
    set "/usr/bin/ruby" "$0" "$*"
  fi
  exec $@
fi
=end
end

## RUBY CODE FOLLOWS...
Why it works is an exercise left to the reader.

Note that this may confuse some editors that base the syntax off the shebang line, such as emacs, though the second line above will make sure that vi/vim work using modeline magic.

For another solution, see RosettaCode


Back to Solutions.

DaveSource.com - Dave's geek site GetDave.com - all the current Dave Pointers. MarginalHacks - I have an elegant script for that, but it's too small to fit in the margin.