From: George Wang Date: 2008-06-03T11:14:05+09:00 Subject: Re: Prevent ruby constant variables from changing? Hi, Thanks to everyone for their helpful replies. Actually I want to be able to encapsulate a variable which is a Firefox browser instance. I tried the following but to no avail. Any ideas? irb(main):001:0> require 'firewatir' irb(main):002:0> include FireWatir irb(main):003:0> module CONSTANT irb(main):004:0> browser=FireWatir::Firefox.start('http://1.2.3.4/') irb(main):005:0> end irb(main):006:0> CONSTANT.constants =>[] irb(main):007:0> CONSTANT::browser NoMethodError: undefined method 'browser' for CONSTANT::Module from (irb):7 George Pe単a, Botp wrote: > From: George Wang [mailto:stdcells@yahoo.com] > # Is there a way I can fix the value that is initially assigned to the > # constant variable? > > arggh, ruby constants are global vars that croaks when you modify them > :) > > i too had this problem, and the closest i can get is to wrap the > constants in a module and then freeze the module. > > eg, > > botp@botp-desktop:~$ irb > > irb(main):001:0> module CONSTANT > irb(main):002:1> X=1 > irb(main):003:1> Y=2 > irb(main):004:1> Z="test" > irb(main):005:1> end > => "test" > > irb(main):006:0> CONSTANT.constants > => ["Z", "Y", "X"] > > irb(main):008:0> CONSTANT::X > => 1 > > irb(main):009:0> CONSTANT::X = 100 > (irb):9: warning: already initialized constant X > => 100 > > irb(main):010:0> CONSTANT::X > => 100 > > irb(main):011:0> CONSTANT.freeze > => CONSTANT > > irb(main):012:0> CONSTANT::X > => 100 > > irb(main):013:0> CONSTANT::X = 99 > TypeError: can't modify frozen module > from (irb):13 > from :0 > > irb(main):014:0> CONSTANT::X > => 100 > > it's a blessing in disguise; i think i may stick to this scheme. > Considering how applications grow and how vars/constants clash, somehow > i feel like i should qualify my constants. It's safer, and readable too. > (and don't worry, there is no unfreeze in ruby ;) > > kind regards -botp -- Posted via http://www.ruby-forum.com/.