S
S.Volkov
Could you please explain me why String instance methods return subclass,
and MyStr#to_s returns String, not the receiver as specified?
# here is the test code
$ cat tStringSubClass.rb
class MyStr < String
def rest
self[1..-1]
end
end
ms = MyStr.new('ABC')
puts \
'I got ' + ms.class.name,
'Expect String, get:',
ms.rest.class,
ms.downcase.class,
ms.succ.class,
ms[1..-1].class,
ms.split(//).map{ |s| s.class },
'Expect MyStr, get:',
ms.to_s.class,
ms.to_str.class
# and here is the result
$ ruby tStringSubClass.rb
I got MyStr
Expect String, get:
MyStr
MyStr
MyStr
MyStr
MyStr
MyStr
MyStr
Expect MyStr, get:
String
String
and MyStr#to_s returns String, not the receiver as specified?
# here is the test code
$ cat tStringSubClass.rb
class MyStr < String
def rest
self[1..-1]
end
end
ms = MyStr.new('ABC')
puts \
'I got ' + ms.class.name,
'Expect String, get:',
ms.rest.class,
ms.downcase.class,
ms.succ.class,
ms[1..-1].class,
ms.split(//).map{ |s| s.class },
'Expect MyStr, get:',
ms.to_s.class,
ms.to_str.class
# and here is the result
$ ruby tStringSubClass.rb
I got MyStr
Expect String, get:
MyStr
MyStr
MyStr
MyStr
MyStr
MyStr
MyStr
Expect MyStr, get:
String
String