Mis*_*hko 11 ruby ruby-on-rails ruby-on-rails-3
在我的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
Run Code Online (Sandbox Code Playgroud)
但是,我收到错误,因为我check_data在定义它之前调用.好吧,我可以将定义放在文件的顶部,但是对于我的意见,文件的可读性会降低.还有其他解决方法吗?
Bri*_*pel 23
在Ruby中,函数定义是与其他语句(如赋值等)完全相同的语句.这意味着在解释器达到"def check_data"语句之前,check_data不存在.因此必须在使用之前定义函数.
一种方法是将函数放在单独的文件"data_functions.rb"中并在顶部需要它:
require 'data_functions'
Run Code Online (Sandbox Code Playgroud)
如果你真的想要它们在同一个文件中,你可以把你所有的主逻辑包装在它自己的函数中,然后在最后调用它:
def main
groups = ...
check_data
save_data_in_database
end
def check_data
...
end
def save_data_in_database
...
end
main # run main code
Run Code Online (Sandbox Code Playgroud)
但请注意,Ruby是面向对象的,在某些时候,您可能最终将逻辑包装到对象中,而不仅仅是编写孤独的函数.
ste*_*lag 11
Andrew Grimm提到END; 还有BEGIN
foo "hello"
BEGIN {
def foo (n)
puts n
end}
Run Code Online (Sandbox Code Playgroud)
您不能使用它来初始化变量,因为{}定义了局部变量范围.
你可以使用END(大写,而不是小写)
END {
# begin of variables initialization
groups = ...
# end of variables initialization
check_data
save_data_in_database
}
Run Code Online (Sandbox Code Playgroud)
但这有点像黑客.
基本上,END代码在所有其他代码运行后运行.
编辑:还有Kernel#at_exit,(rdoc链接)