Rails运行器为简单脚本抛出"未定义的局部变量或方法"错误

Cra*_*lot 0 ruby methods ruby-on-rails ruby-on-rails-3

当我们调用此命令时rails runner test.rb -e production,我们看到此错误:

test.rb:2:in `<top (required)>': undefined local variable or method `hello' for main:Object (NameError)
        from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands/runner.rb:51:in `eval'
        from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands/runner.rb:51:in `<top (required)>'
        from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands.rb:64:in `require'
        from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands.rb:64:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)

test.rb的内容:

hello

def hello
        puts "hi"

end
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我们在Rails 3.2.12上.

Dan*_*sky 6

因为在声明方法之前调用方法.

def hello
  puts "hi"
end

hello
Run Code Online (Sandbox Code Playgroud)