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 に答える