Chris White wrote in post #1014080:
> On Jul 31, 2011, at 4:41 PM, Marc Chanliau wrote:
>
>> end
>>
>> puts "enter a positive integer: "
>> n = gets
>
> Problem one, your factorial function is expecting to work with an
> integer value, but gets returns a string. Instead you can convert it
> straight from gets:
>
> n = gets.to_i
>
>> puts "factorial: " + fact(n)
>>
>
> Next the return value of fact is an integer value, but you're using + to
> concat what is expected to be two strings. Instead you can inline the
> fact call, which will call .to_s on the result in the background:
>
> puts "factorial: #{fact(n)}"
>
> Here's the full code:
>
> def fact(n)
>  if n == 0
>    1
>  else
>    n * fact(n-1)
>  end
> end
>
> puts "enter a positive integer: "
> n = gets.to_i
> puts "factorial: #{fact(n)}"
>
> Regards,
> Chris White
> Twitter: http://www.twitter.com/cwgem

Thanks, that helps a lot.
Now, I want to put that code into a class (in good Ruby fashion, I
guess).
I have this code:

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 `<main>': undefined local variable or method `n' for
main:Object (NameError)

thanks again in advance.

-- 
Posted via http://www.ruby-forum.com/.