Skip to content

Instantly share code, notes, and snippets.

@v-pukman
Last active July 9, 2018 11:42
Show Gist options
  • Save v-pukman/57101606aa9bf7d5987cb69440f680a3 to your computer and use it in GitHub Desktop.
Save v-pukman/57101606aa9bf7d5987cb69440f680a3 to your computer and use it in GitHub Desktop.
ruby_code_solutions
###############
## Factorial ##
###############
# 1:
def fac1 n
v = 1
(1..n).each {|t| v *= t}
v
end
# 2:
def fac2 n
(1..n).inject(1) {|s, i| s *= i }
end
# 3:
def fac3 n
return 1 if n == 1
n*fac3(n-1)
end
# 4:
class Integer
def fac
return self if self == 1
self*(self-1).fac
end
end
[1,2,3,4,5].map(&:fac) # [1, 2, 6, 24, 120]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment