[Q] initializing class variables

Hello,
I want to write a class with a class variable that gets initialized as
soon as the class is defined. Something like this:

class BigFloat
@@precision = 40 # This doesn’t work.

end

The contents of @@precision affect the instantiation of the class, so
it has to be defined before I create any object.

I don’t want to replace @@precision by a constant (PRECISION) because I
want the user to be able to change its value. I’ll write accessor methods
so the user can type:

BigFloat.precision = 50

Does anyone know how I can accomplish this?

Thanks a lot.

···


Daniel Carrera
Graduate Teaching Assistant. Math Dept.
University of Maryland. (301) 405-5137

class BigFloat
@@precision = 40 # This doesn’t work.

end

···

----- Original Message -----
From: “Daniel Carrera” dcarrera@math.umd.edu


Why do you say it doesn’t work? (In other words, how is it not working for
you?)

irb(main):001:0> class Foo
irb(main):002:1> @@bar = 5
irb(main):003:1>
irb(main):004:1* def Foo.bar
irb(main):005:2> @@bar
irb(main):006:2> end
irb(main):007:1> end
nil
irb(main):008:0> Foo.bar
5
irb(main):009:0>

Chris

it works in 1.6.7

(i defined this class in irb, but cleaned it up here to be easy to read)

class Thing
@@cvar = 1
def Thing.cvar
@@cvar
end
def Thing.cvar= new
@@cvar = new
end
def initialize new
@ivar = new + Thing.cvar
end
def ivar
@ivar
end
def ivar= new
@ivar = new
end
end

irb(main):019:0> Thing.cvar
1
irb(main):020:0> t = Thing.new 1
#<Thing:0x80f44d0 @ivar=2>
irb(main):021:0> Thing.cvar = 10
10
irb(main):022:0> Thing.cvar
10
irb(main):023:0> t = Thing.new 1
#<Thing:0x80ed090 @ivar=11>

the class variable gets set when the class is defined, then used to
initialize and object. and it can be changed via class methods, and the
new value is then used in later objects.

is this what you wanted?

-Justin White

just6979@yahoo.com
http://tin.2y.net/
AIM: just6979

···

On Monday, February 17, 2003, at 03:33 , Daniel Carrera wrote:

Hello,
I want to write a class with a class variable that gets initialized as
soon as the class is defined. Something like this:

class BigFloat
@@precision = 40 # This doesn’t work.

end

The contents of @@precision affect the instantiation of the class, so
it has to be defined before I create any object.

I don’t want to replace @@precision by a constant (PRECISION) because I
want the user to be able to change its value. I’ll write accessor
methods
so the user can type:

BigFloat.precision = 50

Does anyone know how I can accomplish this?

Thanks a lot.

Ooops. Actually the problem was on the wrapping function that I wrote.
It was sending a blank value for ‘precision’.

Thanks for the help.

···

On Tue, Feb 18, 2003 at 05:52:39AM +0900, Chris Pine wrote:

Why do you say it doesn’t work? (In other words, how is it not working for
you?)


Daniel Carrera
Graduate Teaching Assistant. Math Dept.
University of Maryland. (301) 405-5137