Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Ruby library from the command-line

I've just learned the basics of Ruby after being very happy with Python for several years (I'm still using Python for some things), but I'd like to know if there's an idiom or hack to solve this particular problem.

I have a Ruby script which I'd like to be able to do require script_name with, but I'd also like to be able to run ruby script_name.rb from the terminal and have it run as a command line script. In Python this would be done by having the following structure at the bottom of the script:

if __name__ == '__main__':
    # do something here

However, I can't seem to find an equivalent in Ruby. Is there a way of detecting whether or not the current script is being run from the command-line? Maybe some Kernel:: method or something? Ideally what I'd like is something like this at the bottom of the script:

if from_command_line?
  # do something here
end
like image 345
zvoase Avatar asked Jan 28 '09 10:01

zvoase


People also ask

How do I run a Ruby script from the shell?

In this case, it's a Ruby file to be executed with the Ruby interpreter. To mark the file as executable, run the command chmod +x test. rb. This will set a file permission bit indicating that the file is a program and that it can be run.


1 Answers

You want to use:

if __FILE__ == $0
  # do stuff
end

__FILE__ is the source file name and $0 is the name of the script currently being executed.

like image 54
Garry Shutler Avatar answered Oct 14 '22 13:10

Garry Shutler