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

时间:2013-06-21 08:22:19

标签: ruby-on-rails ruby ruby-on-rails-3 methods

当我们调用此命令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>'

test.rb的内容:

hello

def hello
        puts "hi"

end

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

2 个答案:

答案 0 :(得分:6)

因为在声明方法之前调用了一个方法。

def hello
  puts "hi"
end

hello

答案 1 :(得分:3)

hello # remove this one.

def hello
        puts "hi"

end

见内省:

defined? hello #=> nil # so here Ruby doesn't know who is "hello",and your call to hello thus throws the error.
def hello
        puts "hi"
end
defined? hello #=> "method"
hello #=> "hi"