Skip to content

Instantly share code, notes, and snippets.

@nbkhope
Last active July 7, 2016 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbkhope/03c0216f2a3784f75330cadfe3ab0826 to your computer and use it in GitHub Desktop.
Save nbkhope/03c0216f2a3784f75330cadfe3ab0826 to your computer and use it in GitHub Desktop.
Introduction to RSpec and Test-Driven Development using Factorial
# Given an integer greater than or equal to zero
def factorial(n)
return 1 if n <= 1
product = 1
index = n
while index > 1
product *= index
index -= 1
end
product
end
require_relative '../factorial'
describe "Factorial" do
it "computes the factorial of 0" do
expect(factorial(0)).to eq 1
end
it "computes the factorial of 1" do
expect(factorial(1)).to eq 1
end
it "computes the factorial of 2" do
expect(factorial(2)).to eq 2
end
it "computes the factorial of 3" do
expect(factorial(3)).to eq 6
end
it "computes the factorial of 4" do
expect(factorial(4)).to eq 24
end
it "computes the factorial of 5" do
expect(factorial(5)).to eq 120
end
it "computes the factorial of 6" do
expect(factorial(6)).to eq 720
end
it "computes the factorial of 7" do
expect(factorial(7)).to eq 5040
end
end
@jondeaton
Copy link

I like writing factorial as recursive:

def factorial(n): if n in [0,1]: return 1 else: return n * factorial(n -1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment