On Mon, Aug 1, 2011 at 3:08 PM, Marc C.
[email protected]wrote:
But I still get an error:
marcc$ ruby factorial7.rb
enter a positive integer: 4
factorial7.rb:11:in <main>': undefined method
fact’ for main:Object
(NoMethodError)
thanks!
I think it is admirable that so many people are willing to take the time
and
effort to help newbies. But I think in this case, the help he needs
isn’t
for you to tell him what is wrong / why it is wrong, but to explain how
you
figured it out.
The error message here is pretty straightforward, it even tells you
where
your program experienced the problem (the line number). Marc, you need
to
study this error message, you will experience it many times, so lets
deal
with it now.
It says “undefined method fact' for main:Object" When you reference something in Ruby (you write some text that isn't a string/symbol/number/etc) then the interpreter goes looking for either a local variable (such as my_fact) or a method (such as fact, which you defined in the Factorial class). In this case, at the top level, methods get defined on Object, and the toplevel is an instance of Object, so that is where it goes looking for methods. Since you have no local variables or methods on Object named fact, the interpreter raises an error saying "undefined method
fact’ for main:Object” (in this case, it doesn’t say
anything about local variables, because it realizes that you passed an
argument to fact, so it must be a method).
Now that you know what is wrong, look at where the error happened in
your
code to get the context. The error tells you that it was raised in
“factorial7.rb:11” So in your file named factorial7.rb, on line 11.
Going there, you can see that you have the line puts "factorial: #{fact(my_fact)}"
Now that we have context, think about what you were
intending, and what the interpreter was expecting. Why don’t they align,
and
what can you do about it?
(and I see that Phillip has already showed you how to fix it, and you’ve
already responded, but I’m going to post this anyway, because I think it
is
imperative that you learn this)