12

我正在使用红宝石 1.8.7。我本可以发誓我之前已经在脚本底部编写了函数并且它运行良好。

我必须把它们放在顶部吗?这似乎是他们现在工作的唯一方式。没有大碍。我只是更喜欢把它们放在底部,所以我想我会问的。

4

2 回答 2

22

您可以在一个或多个 BEGIN 块中初始化代码(继承自 Perl,Perl 继承自 awk)。

can_i_do_this? #=>yes

BEGIN {
  def can_i_do_this?
    puts "yes"
  end
}

为了完整起见,还有 END 块:

END {
  can_i_do_this? #=> yes
}

def can_i_do_this?
  puts "yes"
end
于 2012-07-23T21:09:59.257 回答
6
a
def a
  puts "Hello world!"
end

在 Ruby 中运行这个脚本会给你:

script.rb:1:in `<main>': undefined local variable or method `a' for main:Object (NameError)

所以不,你不能把它们放在底部。由于 Ruby 是一种解释型语言,任何代码都只在运行时被解析和处理。因此,您只能运行在实际引用之前已经定义的代码(调用方法、使用变量...)。

于 2012-07-23T21:06:29.573 回答