Question

Here's what I'm doing:

$ cat 1.rb
#!/usr/bin/env ruby
class A
    @a = 1
    @@b = 2
    def self.m
        p @a
        p @@b
    end
end
class B < A
end
class C < A
    @@b = 3
end
B.m
$ ./1.rb
nil
3

I expected to see 1 and 2. I don't really understand why and what can I do?

Was it helpful?

Solution

These other posts should help you with your question:

Class variables are accessible by subclasses, but instance variables bound to a class object are not.

class A
  @a = 1 # instance variable bound to A
  @@b = 2 # class variable bound to A
end

class B < A; end # B is a subclass of A

# B has access to the class variables defined in A
B.class_variable_get(:@@b) # => 2

# B does not have access to the instance variables bound to the A object
B.instance_variable_get(:@a) # => nil

Instance variables bound to a class object are often referred to as 'class instance variables'.

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