Ruby:如何在定义之前调用函数? [英] Ruby: How to call function before it is defined?

查看:35
本文介绍了Ruby:如何在定义之前调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 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:如何在定义之前调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆