Do I do something wrong here or I cannot override method upcase in
String?
class String
def upcase
super.upcase
end
end
“abc”.upcase
Thanx for any help,
Bojan M.
Do I do something wrong here or I cannot override method upcase in
String?
class String
def upcase
super.upcase
end
end
“abc”.upcase
Thanx for any help,
Bojan M.
On 17/06/06, Bojan M. [email protected] wrote:
Do I do something wrong here or I cannot override method upcase in String?
class String
def upcase
super.upcase
end
end
super is used on its own in a subclass, and indicates the superclass’s
method of the same name:
class MyString < String
def upcase
super + ‘!11’
end
end
s = MyString.new(‘aol’)
s.upcase # => ‘AOL!11’
To modify the original class, use alias_method:
class String
alias_method :original_upcase, :upcase
def upcase
original_upcase + ‘!ELEVEN’
end
end
s = “myspace”
s.upcase # => “MYSPACE!ELEVEN”
I hope that clears it up a bit.
Paul.
On Jun 17, 2006, at 20:48, Bojan M. 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
Matthew S. wrote:
class StringLikeThing < String
You can also redefine the method, if that really is what you’re after.
you can use an alias:
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 M.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs