what is the use of "#!/usr/local/bin/ruby -w" at the start of a ruby program

simminni picture simminni · Jul 3, 2013 · Viewed 42.7k times · Source

what is the use of writing the following command at the start of a ruby program ?

#!/usr/local/bin/ruby -w

Is it OS specific command? Is it valid for ruby on windows ? if not, then what is an equivalent command in windows ?

Answer

Koterpillar picture Koterpillar · Jul 3, 2013

It is called a Shebang. It tells the program loader what command to use to execute the file. So when you run ./myscript.rb, it actually translates to /usr/local/bin/ruby -w ./myscript.rb.

Windows uses file associations for the same purpose; the shebang line has no effect (edit: see FMc's answer) but causes no harm either.

A portable way (working, say, under Cygwin and RVM) would be:

#!/usr/bin/env ruby

This will use the env command to figure out where the Ruby interpreter is, and run it.

Edit: apparently, precisely Cygwin will misbehave with /usr/bin/env ruby -w and try to look up ruby -w instead of ruby. You might want to put the effect of -w into the script itself.