What is "dynamic constant assignment"

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.

Alle martedì 14 agosto 2007, Nikos Kanellopoulos ha scritto:

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

2007/8/14, sean liu [email protected]:

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.

“Any explanations will be appreciated.”

Ruby does not allow redefinitions of constants
in a method.

On 8/14/07, Stefano C. [email protected] wrote:

end

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

Although it might make more sense to do

@AB = 10
def self.AB
@AB
end

def self.AB=(value)
@AB = value
end

Stefano

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