需要在 Ruby 中进行前向声明
我正在尝试在 one 文件中编写 Ruby 脚本。
我想知道是否可以在开头编写“main”函数,并在其后定义 main 使用的其他函数。换句话说,我想调用一个尚未定义的函数,以便它们不依赖于定义顺序。仅更改顺序是不可能的,因为它会给出“未定义的方法”错误。在 C/C++ 中,我们使用前向声明...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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要在
main
函数运行时定义您调用的函数,而不是在定义它时。因此,最简单的解决方案是在脚本开头编写 main 函数,但在末尾调用它。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 themain
function at the script's beginning, but call it at the end.