1

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 #=> "つくえ"
2
  • You can simply reopen class (in this case it would be String class) and define the method you need. But it isn't advisable, especially for Ruby beginners. Commented Nov 14, 2017 at 12:29
  • 2
    @MarekLipka prepending a module is a preferable way since it allows to call super on while overwriting methods. Commented Nov 14, 2017 at 12:31

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You could also wrap the prepend into a Refinement for isolation.
@JörgWMittag I consider 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.
3

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.

Comments

1
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.

1 Comment

This answer brings no additional value to the previously given answer by @SteveTurczyn plus the name of the method is confusing since it does not indeed add the exclamation mark to the receiver, it just returns a receiver appended with an exclamation mark.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.