From: Bojan Mihelac Date: 2006-06-18T05:09:17+09:00 Subject: Re: Overiding method in String Matthew Smillie wrote: > On Jun 17, 2006, at 20:48, Bojan Mihelac wrote: > >> Do I do something wrong here or I cannot override method upcase in >> String? >> >> class String >> def upcase >> super.upcase >> end >> end >> >> "abc".upcase > > That's not overriding the method, but redefining it. Overriding takes > place in subclasses, and you can definitely override the method > (below). You'll also note that super doesn't work quite the same way as > it does in Java - it's not a reference to the superclass, it calls the > overridden method directly; also, the superclass of String is Object, > which doesn't have an upcase method, so you would have had problems > there as well. > > class StringLikeThing < String > def upcase > super > end > end > > str = StringLikeThing.new("foo") > => "foo" > str.upcase > => "FOO" > > You can also redefine the method, if that really is what you're after. > > class String > def upcase > "This used to be the upcase method, now it's gone!" > end > end > "abc".upcase > => "This used to be the upcase method, now it's gone!" > > If you still want to use the old behaviour, but with some modification, > you can use an alias: > > class String > alias :real_upcase :upcase > def upcase > "upcase: " + real_upcase > end > end > "abc".upcase > => "upcase: ABC" > > Hope that helps. > matthew smillie > > > > Thanks for both quick answers, it's all clear now. I used aliasing to redefine module methods. best regards, Bojan Mihelac -- Bojan Mihelac Informatika Mihelac, Bojan Mihelac s.p. | www.informatikamihelac.com -> tools, scripts, tricks from our code lab: http://source.mihelac.org