开发者

rb_str_modify() equivalent in the Ruby language

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 someth开发者_Python百科ing or is there really no possibility in the language itself?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜