Run code only if script called from the command line

前端 未结 1 1970
春和景丽
春和景丽 2021-02-03 21:20

So when I call my script from the command line, I want it to take in an int and do something with the value:

ruby script.rb


puts ARGV[0], etc...
1条回答
  •  抹茶落季
    2021-02-03 21:54

    It is common to put this at the bottom of your script:

    if __FILE__==$0
      # this will only run if the script was the main, not load'd or require'd
    end
    

    Because I like to see the main action at the top of my file, I usually put a def run! as the first method in the file and then end the file with:

    run! if __FILE__==$0
    

    0 讨论(0)
提交回复
热议问题