From: "Jesús Gabriel y Galán" Date: 2009-02-09T04:31:18+09:00 Subject: Re: best way to protect class instance variables On Sun, Feb 8, 2009 at 8:11 PM, Barun Singh wrote: > Suppose I generate a class instance variable and create an accessor > function for it as follows: > > class MyClass > @blah = [0,1] > def self.blah > @blah > end > end > > I would like to prevent any other piece of code from having any way of > changing the value of the class variable. While the code above prevents > me from saying "MyClass.blah = 'hello'", it does allow me to say > "MyClass.blah[0] = 'hello'", which changes the value of the class > instance variable (to ['hello',1]) any time I try to access it in the > future. You could freeze it: irb(main):009:0> class Blah irb(main):010:1> @blah = [0,1].freeze irb(main):011:1> def self.blah irb(main):012:2> @blah irb(main):013:2> end irb(main):014:1> end => nil irb(main):015:0> Blah.blah => [0, 1] irb(main):016:0> Blah.blah[0] = "hello" TypeError: can't modify frozen array from (irb):16:in `[]=' from (irb):16 This could save you from accidental changes, but somebody could always do this and trash your frozen array: irb(main):017:0> class Blah irb(main):018:1> @blah = %w{nothing is really safe} irb(main):019:1> end => ["nothing", "is", "really", "safe"] irb(main):020:0> Blah.blah => ["nothing", "is", "really", "safe"] or this: irb(main):021:0> Blah.send (:instance_variable_set, "@blah", [1,2,3]) (irb):21: warning: don't put space before argument parentheses => [1, 2, 3] irb(main):022:0> Blah.blah => [1, 2, 3] or probably many other things to achieve that. So it's not really safe. Jesus.