Ruby:如何在定义之前调用函数?
在我的seeds.rb
文件中,我希望有以下结构:
# begin of variables initialization groups = ... # end of variables initialization check_data save_data_in_database # functions go here def check_data ... end def save_data_in_database ... end
但是,我收到一个错误,因为我在定义之前调用了check_data
。 好吧,我可以将定义放在文件的顶部,但是根据我的意见,文件的可读性会降低。 还有其他解决方法吗?
在Ruby中,函数定义是与其他语句(如赋值等)完全相同的语句。这意味着在解释器达到“def check_data”语句之前,check_data不存在。 因此必须在使用之前定义函数。
一种方法是将函数放在单独的文件“data_functions.rb”中并在顶部需要它:
require 'data_functions'
如果你真的希望它们在同一个文件中,你可以将所有主逻辑包装在自己的函数中,然后在最后调用它:
def main groups = ... check_data save_data_in_database end def check_data ... end def save_data_in_database ... end main # run main code
但请注意,Ruby是面向对象的,在某些时候你可能最终将逻辑包装到对象中,而不仅仅是编写孤独的函数。
你可以使用END
(大写,而不是小写)
END { # begin of variables initialization groups = ... # end of variables initialization check_data save_data_in_database }
但这有点像黑客。
基本上,在运行所有其他代码之后运行END
代码。
编辑:还有Kernel#at_exit
,( rdoc链接 )
Andrew Grimm提到END; 还有BEGIN
foo "hello" BEGIN { def foo (n) puts n end}
您不能使用它来初始化变量,因为{}定义了局部变量范围。
您可以将这些函数放在另一个文件上,并在脚本的顶部发出请求。
将初始调用包装在函数中并在最后调用该函数:
# begin of variables initialization groups = ... # end of variables initialization def to_be_run_later check_data save_data_in_database end # functions go here def check_data ... end def save_data_in_database ... end to_be_run_later