Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launching Ruby without the prefix "Ruby"

I'm on OS X (with bash) and a newbie at unix. I want to know if it's possible to amend some file such that to run a ruby program, I don't need "ruby file.rb", but instead can just run "ruby.rb".

Is there a reason NOT to do this?

Thanks!

like image 391
Alex Mcp Avatar asked Mar 31 '09 14:03

Alex Mcp


1 Answers

As others have mentioned, you want to have a shebang (#!) line at the beginning, and change the permissions to executable.

I would recommend using #!/usr/bin/env ruby instead of the path to Ruby directly, since it will make your script more portable to systems that may have Ruby installed in different directories; env will search in your search path, and so it will find the same Ruby that you would execute if you ran ruby on the command line. Of course, this will have problems if env is in a different location, but it is much more common for env to be at /usr/bin/env than for Ruby to be at /usr/bin/ruby (it may be in /usr/local/bin/ruby, /opt/bin/ruby, /opt/local/bin/ruby, etc)

#!/usr/bin/env ruby
puts "Hello!"

And make it executable:

chmod +x file.rb
like image 187
Brian Campbell Avatar answered Nov 04 '22 12:11

Brian Campbell