From: David Alan Black Date: 2002-05-04T12:50:46+09:00 Subject: Re: Adding new method to Built-In class Hello -- On Sat, 4 May 2002, Hubert Hung-Hsien Chang wrote: > I have tried to add new method to built-in class without success. > In other words, I do not want to have instance method, expression method > and I do not want to create a new class as a subclass just to add this > new method. > > I want to add to the build-in class by (some how) > > def String.new_method > print "give me a method!" > end > > But this 'new_method' won't work on any instance other than > calling it by itself. In other words, > > a = 'test string' > a.new_method > > only produces error. > > > So any idea? What you need to do is re-open the class String, and define a new instance method: class String def new_method puts "give me a method!" end end "abcde".new_method # => give me a method! Doing it that way will cause every string object to respond to that method. With what you originally did, you actually added a class method to String: def String.new_method puts "give me a method!" end String.new_method # => give me a method! ... so in that case, the object that responds to new_method is the class String itself, rather than individual strings. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav