1

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?

x-yuri
  • 16,722
  • 15
  • 114
  • 161
  • 1
    Avoid class variables where you can, especially when related to inheritance. This is an old (but still great) read on the matter, and it promotes class instance variables, which are great! http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/ – Lee Jarvis May 15 '14 at 20:29

1 Answers1

2

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'.

Community
  • 1
  • 1
Powers
  • 18,150
  • 10
  • 103
  • 108
  • Having `Lee Jarvis`'s [link](http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/) in your post would be advantageous. – x-yuri May 18 '14 at 15:29