当我们调用此命令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上。
答案 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"