Reputation: 3
I'm trying to define factorial method for Fixnum class and I don't know how to pass this Fixnum as an argument to my method. Was trying to write something like that
def Fixnum.factorial(n)
n > 1 ? n * factorial(n-1) : 1
end
though I knew it would be incorrect. So is there some kind of "this" reserved word to access this number?
Upvotes: 0
Views: 663
Reputation: 230286
Something like this:
class Fixnum
def factorial
self > 1 ? self * (self - 1).factorial : 1
end
end
puts 6.factorial
# 720
You know, of course, that this is a silly method of calculating a factorial?
Upvotes: 1