Hi, let me show the following code:
--------------------------
module M
@@var="M"
def var
@@var
end
def self.var
@@var
end
end
class A
include M
def var= v
@@var=v
end
end
a=A.new
a.var
=> "M"
a.var="A"
=> "A"
M.var
=> "A"
--------------------------
WHY is @@var replaced within M module? I do know that this behaviour
exists when inheriting classes, so a children class shares the class
variables of its parent class (which is a documented but undesirable
feature of Ruby). But I didn't expect it to occur using a module as
I'm not inheriting from a class.
In short, don't use class variables within a module, am I right?
Thanks a lot.
--
Iñaki Baz Castillo
<ibc*******>
Including a module inserts that module into the inheritance hierarchy.
class A
end
class B < A
end
module M
end
p B.ancestors
#=> [B, A, Object, Kernel, BasicObject]
class B
include M
end
p B.ancestors
#=> [B, M, A, Object, Kernel, BasicObject]
More details than you'd probably like about this mechanism can be
found in a blog post of mine:
http://carboni.ca/blog/p/Modules-How-Do-They-Work
Michael Edgar
adgar*******
http://carboni.ca/
A class is a module. So the statement should be: don't use class
variables period.
--
Posted via http://www.ruby-forum.com/
Great. Thanks a lot for the information.
--
Iñaki Baz Castillo
<ibc*******>
Right. Is it not planned to change the behaviour of class variables in Rub?
--
Iñaki Baz Castillo
<ibc*******>
I have no idea, you might ask at ruby-core. But there is quite a
consensus not to use them. What is your use case?
As much as I can guess from your example code, class instance
variables should do the trick for you.
e.g.
module A
class << self
attr_accessor :a
end
end
HTH
Robert
--
I'm not against types, but I don't know of any type systems that
aren't a complete pain, so I still like dynamic typing.
--
Alain Kay
Yes, I try to use instance variables (but let's say "class's instance
variables" rather than "class instance's instance variable" XDD).
I was just wondering.
Thanks a lot.
--
Iñaki Baz Castillo
<ibc*******>