Tony Marshle
Tony Marshle

Reputation: 127

Adding custom methods to standard ruby objects

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 #=> "つくえ"

Upvotes: 1

Views: 2104

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

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.

Upvotes: 6

evngcdr
evngcdr

Reputation: 66

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.

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36880

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.

Upvotes: 3

Related Questions