Strange behavior with constants

B

Bill Atkins

------=_Part_22480_17988257.1123008086540
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

I have code similar to the snippet below:

--=20

class X
def initialize &b
self.class.class_eval &b
end
end

class Y < X
def initialize &b
super(&b)
end
end

a =3D Y.new do
CONST =3D 3
end

puts class Y; CONST; end
puts class X; CONST; end

--

Ideally, calling Y's constructor should create a constant in Y and Y alone,=
=20
since self in X#initialize is an instance of Y. However, running this code=
=20
yields 3 and 3 - somehow the constant has been declared in X instead of in=
=20
Y.

What am I doing wrong?

I've tried other variations on self.class.class_eval, including=20
self.instance_eval, eval("b.call", binding), all to no avail. Any help woul=
d=20
be appreciated.

--=20
Bill Atkins

------=_Part_22480_17988257.1123008086540--
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: Strange behavior with constants"

|class X
|def initialize &b
|self.class.class_eval &b
|end
|end
|
|class Y < X
|def initialize &b
|super(&b)
|end
|end
|
|a = Y.new do
|CONST = 3
|end
|
|puts class Y; CONST; end
|puts class X; CONST; end

|Ideally, calling Y's constructor should create a constant in Y and Y alone,
|since self in X#initialize is an instance of Y. However, running this code
|yields 3 and 3 - somehow the constant has been declared in X instead of in
|Y.
|
|What am I doing wrong?

Constant assignment is done in the context determined at compile time,
that means you have defined CONST in the toplevel. Use const_set
method instead.

matz.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top