Reputation: 34513
When we invoke this command, rails runner test.rb -e production
, we see this error:
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>'
Contents of test.rb:
hello
def hello
puts "hi"
end
Why is this happening? We're on Rails 3.2.12.
Upvotes: 0
Views: 1973
Reputation: 118271
hello # remove this one.
def hello
puts "hi"
end
See the introspection :
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"
Upvotes: 3
Reputation: 30463
Because you call a method before you declare it.
def hello
puts "hi"
end
hello
Upvotes: 6