mentby.com
Blog | Jobs | Help | Signup | Login

class variables in modules, annoying



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*******>


Iñaki Baz Castillo Fri, 29 Jul 2011 02:28:18 -0700

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/


Michael Edgar Fri, 29 Jul 2011 02:36:06 -0700

A class is a module.  So the statement should be: don't use class
variables period.

--
Posted via  http://www.ruby-forum.com/


7stud -- Fri, 29 Jul 2011 03:25:33 -0700

Great. Thanks a lot for the information.

--
Iñaki Baz Castillo
<ibc*******>


Iñaki Baz Castillo Fri, 29 Jul 2011 03:32:32 -0700

Right. Is it not planned to change the behaviour of class variables in Rub?

--
Iñaki Baz Castillo
<ibc*******>


Iñaki Baz Castillo Fri, 29 Jul 2011 03:33:10 -0700

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


Robert Dober Fri, 29 Jul 2011 04:17:00 -0700

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*******>


Iñaki Baz Castillo Fri, 29 Jul 2011 04:31:06 -0700



Related Topics

Post a Comment