From: Stefan Lang Date: 2009-01-22T06:09:39+09:00 Subject: Re: String doesnt auto dup on modification 2009/1/21 RK Sentinel : > I'm writing my first largeish app. One issue that gets me frequently is > this: > > I define a string in one class. Some other class references it, and > modifies it. I (somehow) expected that when another referer modifies the > reference, ruby would automatically dup() the string. > > Anyway, through trial and error, I start dup()'ing strings myself. I am > aware of freeze(). > > But would like to know how others handle this generally in large apps. > > - Do you keep freezing Strings you make in your classes to avoid > accidental change > > - Do you habitually dup() your string ? > > Is there some clean way of handling this that I am missing. This is a well known "problem" with all languages that have mutable strings. The solution is simple: * Use destructive string methods only after profiling has shown that string manipulation is the bottleneck. * Don't mutate a string after passing it across encapsulation boundaries. Freezing certain strings can be beneficial in the same way assertions are, habitually duping strings is a bad practice, IMO. Stefan