[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: what is "dynamic constant assignment"

Nikos Kanellopoulos

8/14/2007 8:24:00 AM

2007/8/14, sean liu <seanliugm@gmail.com>:
> hi, all
>
> today i defined a class like this:
> class C
> AB = 10
> def self.set(value)
> AB = value
> end
> end
> then i got this error: SyntaxError: compile error (irb):10: dynamic constant
> assignment.
> Constants can be changed after initialization, but what does this error
> mean?
> Any explanations will be appreciated.
>

Variable AB is a contant, because it starts with a capital letter.
You can only assign a contant value (or expression) to it, once.

3 Answers

Stefano Crocco

8/14/2007 8:28:00 AM

0

Alle martedì 14 agosto 2007, Nikos Kanellopoulos ha scritto:
> 2007/8/14, sean liu <seanliugm@gmail.com>:
> > hi, all
> >
> > today i defined a class like this:
> > class C
> > AB = 10
> > def self.set(value)
> > AB = value
> > end
> > end
> > then i got this error: SyntaxError: compile error (irb):10: dynamic
> > constant assignment.
> > Constants can be changed after initialization, but what does this error
> > mean?
> > Any explanations will be appreciated.
>
> Variable AB is a contant, because it starts with a capital letter.
> You can only assign a contant value (or expression) to it, once.

That's not true. You can assign a value to a constant more than once, even if
ruby will issue a warning:

irb: 001> A = 1
1
irb: 002> A = 2
(irb):2: warning: already initialized constant A
2

I guess that the 'dynamic constant assignment' means that you can assing to a
constant in a method.

Stefano



Marc Heiler

8/14/2007 10:16:00 AM

0

"Any explanations will be appreciated."

Ruby does not allow redefinitions of constants
in a method.
--
Posted via http://www.ruby-....

Roger Pack

9/26/2008 5:03:00 PM

0

>> I guess that the 'dynamic constant assignment' means that you can assing
>> to a
>> constant in a method.
>
>
> And the work around is
> def self.set(value)
> const_set("AB". value)
> end

Or, if you aren't in a class method

def set(value)
self.class.const_set(:AB, value) # can use a symbol
end


Cheers.
-=R
--
Posted via http://www.ruby-....