### Thread: Replay Method Based on User Input

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2010
Posts
61
Rep Power
5

#### Replay Method Based on User Input

Working on some exercises for myself. I am sure this is simple, and something I should be able to do. Nonetheless: I am just trying to get the method 'factorial' to run again when a user replies 'yes' to the 'Do you want to play again?' question.

================

Code:
```def factorial(num)
if num < 0
puts 'You can\'t do that'
puts 'Please enter a number greater then 0'
num = gets.chomp.to_i
elsif num <= 1
1
else
num * factorial(num - 1)
end

end

def play_again

puts "Do you want to play again?"

puts "Enter a number"
num = gets.chomp.to_i
factorial(num)

puts "OK. Goodbye."

else
play_again
end
end

puts "I will determine the FACTORIAL of a number you enter"

num = gets.chomp.to_i

puts "The factorial of #{num} is #{factorial num}"

play_again```
2. Just to be sure, you have it working the first time the user replies yes or no?

If you want to repeat some logic, you will have to use a loop.
Take a look at the While and Until Loops.
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2010
Posts
61
Rep Power
5

Yes, it is working the first time. I did get the following solution from another Ruby resource. With the warning ... 9 should fail with recursion level too deep. This is the problem with recursion style programming, it can get deep fairly quickly. Which I guess would be an issue with any solution. I am still unclear on a few things here though, like I don't get how;
Code:
```puts "I will determine the FACTORIAL of a number you enter"
num = gets.chomp.to_i```
triggers the 'factorial' method (picked that up from the original exercise).

I will keep hacking at it until I understand.

Code:
```def factorial(num)
if num < 0
puts "You can't do that" # use double quotes when you have an apostrophy/single quote in your string.
puts 'Please enter a number greater then 0'
num = gets.to_i  # never use .chomp and .to_i or .to_f like this.  A number NEVER has a carriage return
elsif num <= 1
1
else
num * factorial(num - 1)
end

end

end

def play_again

puts "Do you want to play again?"

if replied_yes? gets
puts "Enter a number"
# num = gets.to_i # don't use .chomp.to_i
puts report factorial gets.to_i
play_again
else
puts "OK, BYE!"
end
end

def report num
"The factorial of #{num} is #{factorial num}"
end

puts "I will determine the FACTORIAL of a number you enter"

num = gets.to_i # use .to_i not .chomp.to.i

puts report num

play_again```