0

I was trying to add a method to the String class. This method should mutate the current string (of course it would be possible to write a not mutating version but I'd prefer the mutating one). I had no idea how to do this and after some googling I found the method rb_str_modify which makes a given string mutable. That's exactly what I need but I couldn't find an equivalent in the Ruby language. Did I miss something or is there really no possibility in the language itself?

1 Answer 1

3

Reopening Classes


All classes in Ruby are open for extension so you can simply do this ...

Class String

    def my_new_method(args)

       # Some sort of modification to self

       self.replace "SOME CALCULATED VALUE"

    end

end

... somewhere in your code. I've modified string a few times in different applications - usually I just put the modifications into one particular module, making it easy to reuse them or remove them as required.


Modifying individual objects


Modifying a class in its entirety is dangerous as it's very difficult to identify all of the consequences - I once broke Merb by modifying a method in the String class. It's much safer to modify particular objects. This is easy in Ruby - you use the extend keyword. You define a module, add your function and then modify the target object. This example ...

module Humor
  def tickle
    "hee, hee!"
  end
end
a = "Grouchy"
a.extend Humor
a.tickle  »  "hee, hee!"

is taken from the Pickaxe book

Chris

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

1 Comment

Thank you very much. #replace is a great idea. It works pretty well for my case. I expect no bad consequences. It's just a little method which is really helpful in general.

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.