什么是遗传

方法是继承的

class A
  def boo; p 'boo' end
end

class B < A; end

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

类方法是继承的

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

class B < A; end

p B.boo # => 'boo'

常量是继承的

class A
  WOO = 1
end

class B < A; end

p B::WOO # => 1

但要注意,它们可以被覆盖:

class B
  WOO = WOO + 1
end

p B::WOO # => 2

实例变量是继承的:

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

class B < A; end

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

请注意,如果你覆盖初始化实例变量而不调用 super 的方法,它们将为零。从上面继续:

class C < A
  def initialize; end
 end

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

类实例变量不会被继承:

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

类变量并不是真正继承的

它们在基类和所有子类之间共享为 1 个变量:

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

class B < A;end

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

从上面继续:

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

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