Ruby:如何在定义之前调用函数?

编程入门 行业动态 更新时间:2024-10-20 16:01:51
本文介绍了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:如何在定义之前调用函数?

本文发布于:2023-11-22 05:42:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   定义   如何在   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!