在我的 seeds.rb 文件中,我希望具有以下结构:
In my seeds.rb file I would like to have the following structure:
# 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.好吧,我可以将定义放在文件的顶部,但是我认为文件的可读性会降低.还有其他解决方法吗?
However, I got an error because I call check_data before it is defined. Well, I can put the definition at the top of the file, but then the file will be less readable for my opinion. Is there any other workaround ?
推荐答案在 Ruby 中,函数定义是与其他语句(例如赋值等)完全一样执行的语句.这意味着直到解释器命中您的def check_data"语句,check_data 不存在.所以函数必须在使用前定义.
In Ruby, function definitions are statements that are executed exactly like other statement such as assignment, etc. That means that until the interpreter has hit your "def check_data" statement, check_data doesn't exist. So the functions have to be defined before they're used.
一种方法是将函数放在一个单独的文件data_functions.rb"中,并在顶部要求它:
One way is to put the functions in a separate file "data_functions.rb" and require it at the top:
require 'data_functions'如果你真的想把它们放在同一个文件里,你可以把所有的主要逻辑都包装在自己的函数中,然后在最后调用它:
If you really want them in the same file, you can take all your main logic and wrap it in its own function, then call it at the end:
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 是面向对象的,在某些时候,您可能最终会将逻辑包装到对象中,而不仅仅是编写单独的函数.
But note that Ruby is object oriented and at some point you'll probably end up wrapping your logic into objects rather than just writing lonely functions.
更多推荐
Ruby:如何在定义之前调用函数?
发布评论