From: Justin Collins Date: 2011-08-03T10:27:17+09:00 Subject: Re: newbie question On 08/01/2011 12:50 PM, Chris White wrote: >> class Factorial >> def fact(n) >> if n == 0 >> 1 >> else >> n * fact(n-1) >> end >> end >> end >> >> my_fact = Factorial.new >> puts "enter a positive integer: " >> my_fact = gets.to_i >> puts "factorial: #{fact(n)}" >> >> I get this error: >> >> marcc$ ruby factorial7.rb >> enter a positive integer: 4 >> factorial7.rb:14:in `
': undefined local variable or method `n' for >> main:Object (NameError) >> > There's two issues here. The first is that you renamed `n` to `my_fact`, so it becomes undeclared as the error mentions. The other is that since fact is now part of the Factorial class, you need to change how fact() is called: > > puts "factorial: #{my_fact.fact(n)}" > > More interesting stuff to help you along the learning path. Right now in order to access your fact function, you have to create a new instance of the class. Instead you can utilize what is known as a singleton method. So the class can be rewritten as such: > > class Factorial > def Factorial.fact(n) > if n == 0 > 1 > else > n * fact(n-1) > end > end > end > > puts Factorial.fact(10) Interesting. I usually see this written as class Factorial def self.fact(n) ... (or using class << self) Also, it seems more natural to have Factorial be a module instead of a class, but that's not something the OP needs to worry about at this point. -Justin