Question

module M

  def f=(x)
    @f= x
  end

  def f
    @f
  end

end

class A
  extend M
end

class B < A
end

A.f= 42
puts A.f
puts B.f

this produces

42
nil

Is @f a class variable to A and B? How do I share a variable between A and B by only writing this into M?

Was it helpful?

Solution

By not using @@f directly, but rather class_variable_set() and class_variable_get(), class variables of A, B and C can be used from within M.

module M

    def f=(x)
        class_variable_set("@@f", x)
    end

    def f
        class_variable_get("@@f")
    end

end

class A
    extend M
end

class B < A
end

class C
    extend M
end

A.f= 42
C.f= 23
puts A.f
puts B.f
puts C.f

this produces

42
42
23

As you can see, the variables are shared by A and B, but not C.

OTHER TIPS

B::A.f will produce the correct result

Class variables may do what you need here:

module M

  def f=(x)
    @@f= x
  end

  def f
    @@f
  end

end

class A
  extend M
end

class B < A
end

A.f= 42
puts A.f
puts B.f

This produces:

42
42

This seems to be closer to the behavior you want:

def M()
  m = Module.new
  m.module_eval <<-HERE
    def f=(x)
      @@f= x
    end

    def f
      @@f
    end
  HERE
  m
end

class A
  extend M()
end

class B < A
end

class C
  extend M()
end


A.f= 42
puts A.f
puts B.f

C.f = 23
puts C.f
puts A.f
puts B.f

Produces:

 42
 42
 23
 42
 42
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top