Ruby 模块前置与派生 [英] Ruby module prepend vs derivation

查看:41
本文介绍了Ruby 模块前置与派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

module Mod   
   def here
     puts 'child'
   end    
end

class A
  prepend Mod
  def here
    puts 'parent'
  end
end

class A
   def here
     puts 'parent'
   end
end

class B < A
  def here
    puts 'child'
  end
end

或者换一种说法:派生一个类是否与在子代码的模块前面添加相同?

Or another way to put it: is derivating a class the same as prepending a module of the child's code?

推荐答案

不,不是.B 只能从一个类继承,而 Mod 可以添加到多个类中.如果你在 B#here 内调用 super,它总是引用 A#here,但在 Mod#here 内,它将引用任何 Mod 类的 #here 实例方法:

No, it is not. B can only inherit from one class, but Mod can be prepended to many classes. If you were to call super inside B#here, it would always refer to A#here, but inside of Mod#here, it will refer to the #here instance method of whatever class Mod was prepended to:

module Mod   
  def here
    super + ' Mod'
  end    
end

class A
  prepend Mod
  def here
    'A'
  end
end

class B
  prepend Mod
  def here
    'B'
  end
end

A.new.here
# => 'A Mod'

B.new.here
# => 'B Mod'

class A
  def here
    'A'
  end
end

class B
  def here
    'B'
  end
end

class C < A
  def here
    super + ' C'
  end
end

C.new.here
# => 'A C'

class C < B
  def here
    super + ' C'
  end
end
# TypeError: superclass mismatch for class C

这篇关于Ruby 模块前置与派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆