0

当我们调用这个命令时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 上。

4

2 回答 2

6

因为您在声明方法之前调用了它。

def hello
  puts "hi"
end

hello
于 2013-06-21T08:24:03.460 回答
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"
于 2013-06-21T08:25:35.700 回答