views:

89

answers:

1

Hi,

I am trying to write a Ruby script in one file.

I would like to know if it is possible to write the "main" function in the beginning, having the other functions that are used by main, defined after it. In other words, I would like to call a not yet defined function, so that they do not depends on definition order. Just changing the order is not possible because it gives an "undefined method" error. In C/C++ we use forward declarations... is there something similar in Ruby or another solution to this?

+5  A: 

You just need the functions you call to be defined when your main function runs, not when it's defined. So, the easiest solution is to write the main function at the script's beginning, but call it at the end.

def main
  foo(42)
  bar(24)
end

# definitions of foo and bar

main
Ash Wilson