From: Aaron Patterson Date: 2012-03-01T08:08:32+09:00 Subject: [ruby-core:43030] return values of methods on String subclasses --huq684BweRXVnRxX Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable It pains me to ask about this, but since Rails subclasses String, I need to ask some questions. If you call a method that returns a substring on an instance of a subclass of string, the subclass is returned: class TranslatedString < String end =20 TranslatedString.new("omg")[0,1].class # =3D> TranslatedString That's fine, except that if the String subclass implements initialize, the initialize method is never called on the new object: class TranslatedString < String def initialize str super @not_translated =3D true end def translated? !@not_translated end end =20 TranslatedString.new("omg").translated? # =3D> false TranslatedString.new("omg")[0,1].translated? # =3D> true This leaves us with instances of TranslatedString whose internal state is incorrect because it had no chance to set up it's internal state. Why do we have this behavior? I would like to propose that we either: 1: Only return instances of String (as a superclass implementation) OR 2: Have `initialize_copy` or some other method called when the new string subclass is created. I prefer number #2. Here is a patch for #2. It may be naive, but my test passes: https://gist.github.com/1945213 Thanks. --=20 Aaron Patterson http://tenderlovemaking.com/ --huq684BweRXVnRxX Content-Type: application/pgp-signature -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (Darwin) iQEcBAEBAgAGBQJPTq6xAAoJEJUxcLy0/6/GZfAH/iYUC46kp3X08yAJhufQLHa/ 9e1iYk7Ho+8prppkCXxmBpZUzo3B6YdfkSRztTGdU7OzQia/I/tNKAJ/5MIAdWap WOobScp1/8jrRs9ijyaKaDabk3MVsByvDx0dFKt/HlQoIy+sPAKMM8fzsVYP/NJh xplplBh8VbAu9+sYCEem39hXgU9L2jngJnkEG2BR6nw6G3nvUH+HOTc8CddSHApl pijn8bePlk01WaOIHyO+s352To9jtCagIQ27ojAfKIds5HTNt+YmxZIo/GPgXxMJ VIICwqu/ySdE+RrEwQNOeolNbO9mIp/TZEQE/O5HWDwFtIupIGH0sEBmrYzkzW4= =BCA3 -----END PGP SIGNATURE----- --huq684BweRXVnRxX--