From: Rick DeNatale Date: 2009-12-22T21:59:30+09:00 Subject: Re: Symbols vs. constants? On Tue, Dec 22, 2009 at 6:02 AM, Bertram Scharpf wrote: > Hi, > > Am Dienstag, 22. Dez 2009, 09:57:28 +0900 schrieb Sonja Elen Kisa: >> How are symbols and constant (capitalized) strings similar or >> dissimilar? They both seem to be used to store text that is not intended >> to change. In what situations should I use one or the other? How should >> I separate them in my brain? > > Constants are variables: > >  X = "hello" >  X = "bye"             # not allowed (just a warning) >  X.replace "bye"       # this is allowed! >  X.freeze >  X.replace "hi again"  # forbidden (TypeError) > > But you can also freeze other variables: > >  x = "foo" >  x.freeze >  x.replace "bar"       # forbidden (TypeError) No you can't freeze variables, you can freeze the objects they reference. ruby-1.8.7-p174 > x = 'foo' => "foo" ruby-1.8.7-p174 > x.freeze => "foo" ruby-1.8.7-p174 > x = 'boo' => "boo" ruby-1.8.7-p174 > A = 'bar' => "bar" ruby-1.8.7-p174 > A.freeze => "bar" ruby-1.8.7-p174 > A = 'baz' (irb):6: warning: already initialized constant A => "baz" ruby-1.8.7-p174 > A => "baz" Variables in Ruby are not objects, nor do they contain objects, they refer to objects. Object#freeze prevents future changes to the state of an object, no matter how it is referenced, and it does nothing to prevent the (re)binding of variables. And as for warnings vs. errors. IMHO, warnings are just that, warnings. They warn of something which might be, and sometimes usually will be a problem, but not always. In most cases, the response should be to do whatever need be done to eliminate them, but sometimes they are warnings in the sense of "fasten your seatbelt" or "slippery when wet." Redefining a "Constant" can be useful as times. And some time warnings, like "parenthesize argument(s) for future version", turn out to be non-warnings when the envisioned future version (of the Ruby parser) is abandoned. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale