How to make self executing ruby scripts in Linux?

#!/usr/bin/ruby puts “The ruby code, starts from line 2” How does this work? A program is executed using a tool known as program loader. In linux when a program loader loads the file for execution and sees that there is #! notation in the first line, it would understand that this program needs to be passed to an interpreter program for execution. In case our ruby script when it gets executed ( $./program_name.rb) the program loader would pass it on to the ruby interpreter program that is defined in the hash-bang line as /usr/bin/ruby. Thus the program loader would pass the file name and path to the ruby interpreter, in short the command $ruby program_name.rb ( $/usr/bin/ruby program_name.rb) would be execute. Since the hash-bang line starts with hash ruby interpreter would consider it as a command line only. The last and Final STEP ( IMPORTANT ) In Linux and any other UNIX like operating system no system can execute unless it is given the permission to execute. So we use the command chmod to give the permission to execute.

$chmod 755 program_name.rb 
Following these steps you can make a ruby scrip executable. Note :- The above mentioned method is not for ruby alone, any script can be made self executable using the above mentioned steps. We just have to change the program that is suppose to execute the program .
#!/bin/sh
#!/bin/csh
#!/usr/bin/perl -T
#!/usr/bin/php
#!/usr/bin/python -O
#!/usr/bin/ruby
Also the above mentioned is the location of the interpreter program if its in a different location then you will have to use that location or could use env – enviornment variable in linux thus the hash-bang statement changes to
#!/usr/bin/env ruby
That is the interpreter is searched among the enviorment variable, thus during run time the appropriate interpreter would be searched and used. For more details see the env wikipedia page Happy Coding…]]>