Running ruby scripts from the command line

30 Jan 2019

I recently learned how to write shell scripts and execute them without the need to declare the absolute path to the executable file. Given that I am a ruby developer, the logical progression from this was to work out how I can execute a ruby file in the same manner. While shell scripts require you to declare that you want the shell program to run them using #!/bin/sh ruby scripts require something a little different.

#!/usr/bin/env ruby

my_friends = %w(Adam Alice Lydia Sam)

puts "My best friends are #{my_friends.join(',')}."

#=> "My best friends are Adam, Alice, Lydia, Sam.

Here you can see that we declare that we want Ruby interpreter to execute our ruby file with the line #!/usr/bin/env ruby. Then following this we can write any of the ruby code we require. In this case the program just prints a list of my friends. The trick that allows you to run this program from anywhere on your machine is by placing this file in the ~/bin directory. This way you don't need to specify the absolute path to the file each time. The next challenge will be to create a shell script that will allow execution without the file extension!