From: sawadatsuyoshi@... Date: 2015-01-28T22:45:33+00:00 Subject: [ruby-core:67871] [ruby-trunk - Bug #10795] to_s returns references to self if called on string Issue #10795 has been updated by Tsuyoshi Sawada. Marc-Andre Lafortune wrote: > In any case, your code is better written > > def coords_to_string > "#{latitude},#{longitude}" > end or def coords_to_string [latitude, longitude].join(",") end ---------------------------------------- Bug #10795: to_s returns references to self if called on string https://bugs.ruby-lang.org/issues/10795#change-51273 * Author: Francesco Boffa * Status: Rejected * Priority: Low * Assignee: * ruby -v: ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0] * Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN, 2.2: UNKNOWN ---------------------------------------- This is not actually a bug, but rather a strong violation of the Principle of least astonishment. Lately I found a bug in the Rails project I work to. There was a method concatenating two float values with a comma, converting them to string like this: ~~~ def coords_to_string latitude.to_s << "," << longitude.to_s end ~~~ The bug happened when we passed latitude and longitude as strings instead of floats. Actually, `5.12345.to_s` returns a new string object and any operation made on that string wont affect the original 5.12345. Instead `"5.12345".to_s` will return the same instance of that string, so that the `<<` method will affect the original string. So we found that our latitude variable was growing on each call and after a while it become "5.12345,13.12345,13.12345,13.12345,13.12345,13.12345" This was probably made like this for performance reasons, however we found it a clear violation of the POLA, whereas we expected to_s to always return a new instance of that string. Hope, this may help. Francesco Boffa -- https://bugs.ruby-lang.org/