How to use a class_variable into a Module

Hi, I want to declare a class_variable in class A.
Class A includes a Module M and I want some methods in M using the
class_variable but I get some problem:


module M
def kk
#puts (eval %{ #{send(‘class’).class_variables[0]} })
puts @@class_var
end
end

class A
include M
@@class_var = “kaka1”
end

a = A.new
a.kk
NameError: uninitialized class variable @@class_var in M
from ./class_attr1.rb:4:in `kk’

I understand the problem. Because the nature of class variables when
the Module M uses @@ it looks into a class variable defined in same
class/module.

Is there any way I could use a class A @class_var into a included M
module methods? If not then I’ll use a normal attribute but I don’t
like it since it’s a constant value that could perfectly be a class
variable instead of initialiting it in each A instance creation.

Thanks a lot.

Hi,

Iñaki Baz C. wrote:

Hi, I want to declare a class_variable in class A.
Class A includes a Module M and I want some methods in M using the
class_variable but I get some problem:


module M
def kk
#puts (eval %{ #{send(‘class’).class_variables[0]} })
puts @@class_var
end
end

class A
include M
@@class_var = “kaka1”
end

a = A.new
a.kk
NameError: uninitialized class variable @@class_var in M
from ./class_attr1.rb:4:in `kk’

I understand the problem. Because the nature of class variables when
the Module M uses @@ it looks into a class variable defined in same
class/module.

Is there any way I could use a class A @class_var into a included M
module methods? If not then I’ll use a normal attribute but I don’t
like it since it’s a constant value that could perfectly be a class
variable instead of initialiting it in each A instance creation.

Here is a working code:

module M
@@class_var = nil
def kk
puts @@class_var
end
end

class A
include M
@@class_var = “kaka1”
end

a = A.new
a.kk

Regards,

Park H.

2008/5/19, Heesob P. [email protected]:

class A
include M
@@class_var = “kaka1”
end

a = A.new
a.kk

It’s great!
Thanks a lot.

2008/5/19, Heesob P. [email protected]:

class A
include M
@@class_var = “kaka1”
end

Hi, sorry but that is not valid (at least in my case). If you include
M module in more clases, each one with its own @@class_var, then
@@class_var will be shared between them that it’s not the expected
behaviour:


module M
@@class_var = nil

def kk
puts @@class_var
end
end

class A
include M
@@class_var = “@@ A”
end

class B
include M
@@class_var = “@@ B”
end

a=A.new
a.kk
=> @@ B
(it’s should be “@@ A” )