I am still new to Ruby and basically just writing my first micro-program after finishing Cooper’s book. I was pointed to the direction of avoiding monkey patching but the problem is I don’t know what are the alternatives to achieve the same behavior. Basically, I want to add a new method that is accessible by every string object. The obvious monkey-patching way is to:
class String def do_magic ...magic... end end
I recall there’s a way using String.send. But I can’t remember how it’s done nor where I read it. Can anyone point out any alternatives that would still let me make that method available to the String class and child objects?
Any other way of doing this would just be a more awkward syntax for monkey patching. There are ways involving
sendandevaland all sorts of things, but why? Go ahead and do it the obvious way.You want to be careful of monkey patching in big projects or when you have dependencies, because you can wind up with conflicts when several hands are all messing around in the same place. This doesn’t mean look for an alternative syntax that accomplishes the same thing — it means be careful when you’re making changes that could affect code that’s not yours. This probably isn’t a concern in your particular case. It’s just something that might need to be addressed in larger projects.
One alternative in Ruby is that you can add methods to a single object.