[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Defining constants in global scope

Austin Ziegler

9/19/2003 11:58:00 PM

On Sat, 20 Sep 2003 07:48:10 +0900, Peter wrote:
> Look at the transscript below. Apparently toplevel constants don't really
> belong to the Kernel module. However if a constant is defined at the
> toplevel, and doesn't clash with a constant in the Kernel module, you can
> access it in the Kernel module, but you get a warning. Also toplevel
> constants can be read as ::MyConstant, but not assigned. Somehow this
> behavior seems a bit inconsistent to me. Also I would never allow access
> to toplevel constants through the Kernel module because if you use
> someone else's code which defines a constant with the same name in the
> Kernel module (should someone ever want to do such a thing), you're in
> for one big bug hunting safari. But that's why it gives a warning I
> guess, but it's human nature to ignore warnings, especially when the code
> still works...

Remember that "toplevel" is an instance of Object.

irb(main):001:0> self
=> main
irb(main):002:0> self.class
=> Object
irb(main):003:0> Foo = :foo
irb(main):004:0> Object.const_defined?("Foo")
=> true
irb(main):005:0> Kernel.const_defined?("Foo")
=> false
irb(main):006:0> String.const_defined?("Foo")
=> false
irb(main):007:0> String.instance_eval { p Foo }
:foo
irb(main):008:0> String::Foo
(irb):8: warning: toplevel constant Foo referenced by String::Foo
=> :foo
irb(main):009:0> class String
irb(main):010:1> Foo = :bar
irb(main):011:1> end
=> :bar
irb(main):012:0> String::Foo
=> :bar
irb(main):013:0> class Object
irb(main):014:1> Bar = :baz
irb(main):015:1> end
=> :baz
irb(main):016:0> Bar
=> :baz
irb(main):017:0> String::Bar
(irb):17: warning: toplevel constant Bar referenced by String::Bar
=> :baz

Make sense now?

-austin
--
austin ziegler * austin@halostatue.ca * Toronto, ON, Canada
software designer * pragmatic programmer * 2003.09.19
* 19.49.15



1 Answer

Thomas Sondergaard

9/20/2003 12:38:00 AM

0


> Make sense now?

Well what doesn''t make sense to the OP (me!) is that I can read constants
like this:

::MyConst

::MyModule::MyOtherConst

::MySecondModule::MyOtherConstAgain


and I can define constants like this:

::MyModule::MyOtherConst = "blah"

::MySecondModule::MyOtherConstAgain = "more blah"

But I can''t assign like this:

::MyConst = "blah again"

The toplevel scope is thus somehow different, which is a bit annoying
because I have to treat it as a special case. As a principle I will not
state whether I was the least surprised by it either.

Thomas