LoginSignup
5
5

More than 5 years have passed since last update.

Rubyスクリプトでmainする

Last updated at Posted at 2018-05-22

Rubyで50行くらいの小物スクリプトを作る
→気がついたら色々増えてメソッドに分割する(だいたい100行)
→気がついたら色々増えてファイルに分割する(だいたい300行)
→ところでこれ、どこがトリガーになってるの?

みたいな事が稀によくある。
そういう時にmainが欲しくなる事がある。
Goとかにあるアレ。

やり方はあまり難しくなく、以下のような感じにすると良い。

hoge.rb
def main
  # あれとかこれとか
end

if __FILE__ == $0
  main
end

このファイルをruby hoge.rbのように実行すると、main内の処理が実行される。

ちなみに、__FILE__は自身のファイルを指し、$0実行されたファイルを指す。
要するに「呼び出されたファイルが自分の時に実行してね」という事。

5
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5