From: Brian Candler Date: 2009-01-22T06:57:57+09:00 Subject: Re: String doesnt auto dup on modification RK Sentinel wrote: > 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 ? Generally, no. Of course there is no contract to enforce this, but in many cases it would be considered bad manners to modify an object which is passed in as an argument. If you only read the object, then it doesn't matter. If you need a modified version, create a new object. Usually this doesn't require 'dup'. def foo(a_string) a_string << "/foo" # bad a_string = "#{a_string}/foo" # good a_string = a_string + "/foo" # good end DEFAULT_OPT = {:foo => "bar"} def bar(opt = {}) opt[:foo] ||= "bar" # bad opt = DEFAULT_OPT.merge(opt) # good end If you are paranoid, you can freeze DEFAULT_OPT and all its keys and values. Sometimes you will see frozen strings as an optimisation to reduce the amount of garbage objects created: ... foo["bar"] # creates a new "bar" string every time round BAR = "bar".freeze ... foo[BAR] # always uses the same object This probably won't make any noticeable difference except in the most innermost of loops. -- Posted via http://www.ruby-forum.com/.