开发者

Needing forward declaration in Ruby

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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜