Last active
July 9, 2018 11:42
-
-
Save v-pukman/57101606aa9bf7d5987cb69440f680a3 to your computer and use it in GitHub Desktop.
ruby_code_solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############### | |
## 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