From: Rick DeNatale Date: 2009-06-16T01:50:24+09:00 Subject: Re: confusion about object method scoping On Mon, Jun 15, 2009 at 12:31 PM, Christopher Carver wrote: > Hello, > > I am defining a class.  That class has several methods.  In one of the > class methods I'm trying to use a previously defined method.  It's > throwing an exception.  Here's some code that demonstrates my problem. >  Am I really unable to have a class use some of it's own methods if > they've already been defined?  Thanks in advance! > > class Calculator > >  private >  def add(x,y) >   x+y >  end This defines a method add which any instances of the class Calculator would have, if you had any, which you don't in this code. > >  public >  def Calculator.factorial(x) >   result = 0 > >   (1..x).each { |number| >     result = add(result,number) >   } > >   result >  end > > end And this defines a method on the object which is the class called Calculator. Since Calculator isn't an instance of Calculator it doesn't have an add method. Now how to fix it. One way is class Calculator class < self def factorial(x) result = 0 (1..x).each { |number| result = add(result,number) } result end def add(x, y) x + y end end end puts Calculator.factorial(5) Another way is to actually use an instance of Calculator: class Calculator def factorial(x) result = 0 (1..x).each { |number| result = add(result,number) } result end def add(x, y) x + y end end puts Calculator.new.factorial(5) BTW. I've not mentioned until now that your factorial is actually computing the sum instead of the factorial, because I think that's a separate issue. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale