Skip to content

Instantly share code, notes, and snippets.

@mfpiccolo
Last active December 11, 2015 06:58
Show Gist options
  • Save mfpiccolo/4562495 to your computer and use it in GitHub Desktop.
Save mfpiccolo/4562495 to your computer and use it in GitHub Desktop.
Enter an integer and the program will return the factorial.
#defining the method and argument
def factorial(number1)
#string exception
if number1.kind_of? String
"Enter a number, smartass."
#array exception
elsif number1.kind_of? Array
"Just one number buddy."
#negative numbers exception
else
if number1 < 0
"The factorial of negative numbers are undefined."
#0 exception
elsif number1 == 0
1
#Main calculation
elsif number1.kind_of? Integer
array1 = []
array1 << number1
array1 << number1 -= 1 until number1 <= 1
array1.inject(1) {|x, y| x * y }
#fraction exception
else
"Number must be an integer. Think whole numbers."
end
end
end
#unit tests:
puts "'#{factorial('a')}' should be 'Enter a number, smartass.'"
puts "'#{factorial([1,2,3])}' should be 'Just one number buddy.'"
puts "'#{factorial(-5)}' should be 'The factorial of negative numbers are undefined.'"
puts "'#{factorial(0)}' should be '1'."
puts "'#{factorial(5)}' should be '120'."
puts "'#{factorial(12)}' should be '479001600'."
puts "'#{factorial(3.23)}' should be 'Number must be an integer. Think whole numbers'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment