From: Jason Voegele Date: 2002-09-26T20:51:50+09:00 Subject: Re: Const vs warning J.Leuzinger wrote: >Hi, >Although a newbie, I am really impressed of this powerful and consistent >language ! >Accidently I used the << operator instead of the + operator to concatenate >two strings. >The result was a bit surprising (but intelligibly if one uses the wrong >method). >What bothers me is that Ruby does not issue a warning when a Const String is >modified by the << operator. >If I use the += operator I get a warning. >This seems to me a breach in terms of least surprise. >Do I overlook something ? > When you create a constant in Ruby (by capitalizing the variable name) only the *reference* is constant, not the object it refers to. That means that you will receive a warning if you attempt to make the reference refer to another object, but you are free to change the object that it is referring to: CONST1 = 'Text1' CONST1 = 'Text2' # <- This will give warning The << operator modifies a string in place, so it does not modify the reference to the string. This is why you will not get a warning. The += operator, on the other, creates a new string that is a concatenation of its two operands, and then assigns the new string to the reference. This is why you get a warning for += but not <<. If you would like to make the string object itself const, use freeze: CONST1.freeze This way you will not be able to modify the string. -- Jason Voegele "We believe that we invent symbols. The truth is that they invent us." -- Gene Wolfe, The Book of the New Sun