From: "Peña, Botp" Date: 2008-05-23T19:58:00+09:00 Subject: Re: Prevent ruby constant variables from changing? From: Robert Dober [mailto:robert.dober@gmail.com] # ff is my limited understanding of ruby.. pardon in advance.. # irb(main):001:0> class A # irb(main):002:1> end # => nil here we defined a class object referenced by a constant A, ruby gives the object a name "A". The name "A" is now set in stone :) Consider "A" as the name of A, or the name of object named A. ...arggh, this reminds of me something... No worry, it's just a name.. :) # irb(main):003:0> B = A # => A we copy the constant A to constant B. B now points to class pointed by A wc is still named "A". # irb(main):004:0> class B # irb(main):005:1> def a; 42 end # irb(main):006:1> end # => nil we define a method a in class referred by constant B, wc is A, ergo we are reopening A. # irb(main):007:0> A.new.a # => 42 ok # irb(main):008:0> B.name # => "A" the (class) object referred to by B is still named "A". Stoned. Even if you remove constant A, B.name will still be "A" (note, you just operationaly demonstrated what XNoria wrote in prev post :) # I just feel to think more seriously now never to use "class X" again, # I want to avoid the very subtle inconsistencies it implies but I # really hate, that after # # C = Class::new # C.name equals "C". ruby's behaviour is to get the class name fr the very first constant it encounters or it is assigned to. yes, by the very fact that _it_ is a constant. sorry, but what could be simpler? We've assigned it to a constant, and still we expect it to have no name?? But hey, again, it's just a name. maybe what is confusing here is the word "name" itself :) irb(main):001:0> A=B=C=Class.new => C irb(main):002:0> A.name => "C" irb(main):003:0> B.name => "C" irb(main):004:0> C.name => "C" constant C is not coupled w name "C", see, irb(main):007:0> Object.send :remove_const, :C => C irb(main):008:0> C.name NameError: uninitialized constant C from (irb):8 from :0 irb(main):009:0> A.name => "C" irb(main):010:0> B.name => "C" # irb(main):001:0> C = _ = Class::new # => C # irb(main):002:0> C.name # => "C" # # but finally # # irb(main):006:0> _ = Class::new # => # # irb(main):007:0> _.name # => "" in ruby1.9, this is nil. wc mean, we have no name yet. better than saying my name is empty. btw, careful w using "_" in irb, since irb uses it :) # irb(main):008:0> X = _ # => "" of course, since the last result was "" # irb(main):009:0> X.name # NoMethodError: undefined method `name' for "":String # from (irb):9 # from :0 # irb(main):010:0> as expected kind regards -botp