Ruby Language What is inherited?


Example

Methods are inherited

class A
  def boo; p 'boo' end
end

class B < A; end

b = B.new
b.boo # => 'boo'

Class methods are inherited

class A
  def self.boo; p 'boo' end
end

class B < A; end

p B.boo # => 'boo'

Constants are inherited

class A
  WOO = 1
end

class B < A; end

p B::WOO # => 1

But beware, they can be overridden:

class B
  WOO = WOO + 1
end

p B::WOO # => 2

Instance variables are inherited:

class A
  attr_accessor :ho
  def initialize
    @ho = 'haha'
  end
end

class B < A; end

b = B.new
p b.ho # => 'haha'

Beware, if you override the methods that initialize instance variables without calling super, they will be nil. Continuing from above:

class C < A
  def initialize; end
 end

c = C.new
p c.ho    # => nil

Class instance variables are not inherited:

class A
    @foo = 'foo'
    class << self
        attr_accessor :foo
    end
end

class B < A; end

p B.foo # => nil

# The accessor is inherited, since it is a class method
#
B.foo = 'fob' # possible

Class variables aren't really inherited

They are shared between the base class and all subclasses as 1 variable:

class A
    @@foo = 0
    def initialize
        @@foo  += 1 
        p @@foo
    end
end

class B < A;end

a = A.new # => 1
b = B.new # => 2

So continuing from above:

class C < A
  def initialize
    @@foo = -10
    p @@foo
  end
end

a = C.new # => -10
b = B.new # => -9