Monkey patch in Fixnum class

Hi, I’m kinda new to ruby so there are some things which I’m not sure
which is the best approach.

Right now I’m needing a factorial function, and it doesn’t exists in
Fixnum class. So I thought about monkey patching this class and adding
the factorial method there.

The problem is that I read that monkey patching isn’t a very recommended
thing to do.

Does monkey patching in this case makes sense? Which would be a better
approach than that. And I’m using rails 4, so where should the monkey
patching code go?


This works:

class Fixnum

def factorial
i = self
return 1 if i <= 1
tot = i
until i <= 1 do
i = i - 1
tot = tot * i
return tot


puts 5.factorial

Just be sure that the class code appears first.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs