From: Charlie Date: 2006-04-30T23:44:46+09:00 Subject: Re: Constant in Ruby. Mike Fletcher wrote: $ cat spork #!/usr/local/bin/ruby A_NUMBER = 10 puts "A_NUMBER is #{A_NUMBER}" A_NUMBER = 20 puts "A_NUMBER is #{A_NUMBER}" A_STRING = "foo" puts "A_STRING is #{A_STRING}" A_STRING.sub!( %r/^f/, "b" ) puts "A_STRING is #{A_STRING}" A_STRING.freeze begin A_STRING.sub!( %r/^.*$/, "this won't work" ) rescue TypeError => e warn "sub! on A_STRING failed: #{e}" end A_STRING = "this will work but causes a warning" print "A_STRING is #{A_STRING}" $ ruby spork A_NUMBER is 10 spork:5: warning: already initialized constant A_NUMBER A_NUMBER is 20 A_STRING is foo A_STRING is boo sub! on A_STRING failed: can't modify frozen string spork:20: warning: already initialized constant A_STRING A_STRING is this will work but causes a warning > Reassigning to a constant after the initial assignment causes a warning, > but it works. > > The String instance in A_STRING has methods which will change the > contents of the instance. The constant name "A_STRING" still points to > the same String instance (so I didn't get the warning that I was > reassigning to an already initialized constant), but its internal > state/contents can still be modified in place. Using freeze makes it so > that that internal state can't be changed and the second in-place > substitution call throws an exception. Since I placed begin / rescue / > end around that call I can recovered, but A_STRING would still be "boo". > > Lastly, even though I've frozen the particular instance A_STRING points > to I can still reassign a new String instance to A_STRING. However this > produces the warning that I'm altering an already initialized constant > just as the first examples with A_NUMBER did. And A_STRING is once > again mutable since the new instance hasn't been frozen. Thanks Mike for clearing things up. That helps. -- Posted via http://www.ruby-forum.com/.