From: Robert Klemme Date: 2009-04-25T17:10:39+09:00 Subject: Re: hygienic startup file On 25.04.2009 00:04, Thomas Hafner wrote: > Robert Klemme wrote/schrieb <9e3fd2c80904240015h11f3376l424a24457691b0c0@mail.gmail.com>: > >> The question is: why do you need constants if you want to hide them? > > First I defined constants rather than variables simply because each of > them actually is constant rather than variable: the value never > changes after assignment. In C++ I would add a const qualifier to the > local variables, e.g. to prevent from unintentionally overriding it. > In Haskell ther's no need for a const keyword, because all definitions > are immutable per se, which is regarded a feature in this purely > functional programming language. Keep in mind that Ruby constants are not really constant: robert@fussel ~ $ ruby19 -e 'X=1;puts X;X=2;puts X' 1 -e:1: warning: already initialized constant X 2 Generally, Ruby is less strict with these things ("private" is another example). > But in Ruby there are no local constants analogical to local > variables, so when I simply define constants I unintentionally export > them, too. (Freeze is no option, because it freezes the object hold by > the variable, not the variable itself.) > > Every alternative has its own tradeoff: > 1. If I define simple constants, I pollute the namespace of the > loading code. > 2. If I define constants within class << Object.new, the code is > somehow ugly. This is also a kind of inappropriate solution because you create an instance just to get at its singleton class. This is not needed (see below). > 3. If I define local variables, I don't benefit from the fact that > they are actually constant. > > So currently alternative #3 is best for me, but if somebody shows me a > way to make #2 less ugly (get away from class << Object.new), that > would probably my favorite. You can use an anonymous module for this: robert@fussel ~ $ ruby19 < Module.new do > TEST = 123 > puts "Test is #{TEST}" > end > puts "Is there TEST?" > puts TEST > EOF Test is 123 Is there TEST? -:6:in `
': uninitialized constant TEST (NameError) robert@fussel ~ $ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/