From: Mike Fletcher Date: 2006-04-30T21:02:36+09:00 Subject: Re: Constant in Ruby. Charlie wrote: [...] >> >> It's constant in that you can't reassign a different instance to the >> same name (try setting X = 10 after you've set it to 20 and Ruby will >> gripe). The instances themselves may still be mutable (see >> Object#freeze if you want to change that). > > okay, I just try this: > > X = 20 > X = 10 > puts(X) > 10 > X.freeze > X = 30 > puts(X) > 30 > > Sorry, but I find it difficult to understand as I'm new to it. Would > be helpful if you can enlighten me with some examples. Thanks. $ 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. -- Posted via http://www.ruby-forum.com/.