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

问题描述 投票:0回答:5

在我的

seeds.rb
文件中,我希望具有以下结构:

# Start 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-on-rails ruby ruby-on-rails-3
5个回答
29
投票

在 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 是面向对象的,在某些时候您可能最终会将逻辑包装到对象中,而不仅仅是编写孤独的函数。


13
投票

安德鲁·格林提到了END;还有开始

foo "hello"


BEGIN {
def foo (n)
  puts n
end}

您不能使用它来初始化变量,因为 {} 定义了局部变量范围。


11
投票

您可以使用

END
(大写,而不是小写)

END {
  # begin of variables initialization
  groups = ...
  # end of variables initialization
  check_data
  save_data_in_database
}

但这有点麻烦。

基本上,

END
代码在所有其他代码运行之后运行。

编辑:还有

Kernel#at_exit
,(rdoc链接


3
投票

您可以将函数放在另一个文件中,并在脚本顶部发出请求。


1
投票

将初始调用包装在一个函数中,并在最后调用该函数:

# 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
© www.soinside.com 2019 - 2024. All rights reserved.