Chuck Smithson Chuck Smithson - 1 month ago 12
Ruby Question

User input to create factorial

Need some help on making the

def fact(n)
command to work off user input. My script works great when I input something like "Ruby factorial.rb 5". However, I need this to run with prompts. The script should run something like:

puts 'Please input a non-negative integer:'
n = gets.chomp.to_i
puts "The factorial of #{n} is #{factorial}


Here's what my code looks like now. Like I said however, it does work. It's when I add
n = gets.chomp.to_i
before the
def fact(n)
command that I automatically receive a value of 1. It doesn't matter what number the user puts in, it always returns 1.

#!/user/bin/ruby
def fact(n)
if n==0
1
else
n * fact(n-1)
end
end
puts fact(ARGV[0].to_i)


How do I make this work with the user input? I think I'm just having a syntax issue, but don't know how to make it work.

Answer

You actually seem to be asking for two different things. The first thing you want is an application that does something like this

$ ruby factorial.rb
> Please input a non-negative integer
(GET USER INPUT)
> The factorial of (USER INPUT) is (FACTORAIL OF USER INPUT)

And a command line tool that does something like this

$ fact 10
> 3628800

The first one could look something like this

def fact(n)
  (1..n).inject(:*)
end
puts 'Please input a non-negative integer'
a = gets.to_i
puts "The factorial of #{a} is #{fact(a)}"

The second one could look something like this

#!/usr/bin/ruby
puts (1..ARGV[0].to_i).inject(:*)