How can I add custom methods to standard ruby objects, such as strings and integers?
I have seen this in, for example, rails, and the mojinizer library for ruby that can convert a romaji string into hiragana, as in
"tsukue".hiragana #=> "つくえ"
If you indeed feel a necessity to extend default behavior of classes you do not own (which is basically a very bad idea, one should use other ways to achieve this functionality,) you should not re-open classes, but Module#prepend a module with the requested functionality instead:
String.prepend(Module.new do
def uppercase!
self.replace upcase
end
end)
str = "hello"
str.uppercase!
#⇒ "HELLO"
str
#⇒ "HELLO"
If the method to be overwritten existed in the class, it might still be accessed with a call to super from inside the module method.
prepend into a Refinement for isolation.refinements an absolute evil and never use them, because the cat that barks here and moos there is much worse contract than the cat that meows everywhere. Refinements-related issues are incredibly hard to diagnose, locate and debug. Whether I do not need the cat to bark somewhere, I’d better implement a proxy and delegate.Just open the class and add the method. You can open a class as many times as you need to.
class Fixnum
def lucky?
self == 7
end
end
95.lucky?
=> false
7.lucky?
=> true
It's a useful ability and we've all done it. Take care that your code is maintainable and that you don't break basic functionality.
class String
def add_exclamation_mark
self + "!"
end
end
> "hello".add_exclamation_mark
"hello!"
That way you are adding new methods to a String class.
Stringclass) and define the method you need. But it isn't advisable, especially for Ruby beginners.superon while overwriting methods.