更详细地说,我有一个模块Narf,它为一系列类提供了基本功能.具体来说,我想影响继承Enumerable的所有类.所以我把Narf包含在Enumerable中.
Array是一个默认包含Enumerable的类.然而,它并没有受到Narf在模块中的后期加入的影响.
有趣的是,在包含之后定义的类从Enumerable获得Narf.
例:
# This module provides essential features module Narf def narf? puts "(from #{self.class}) ZORT!" end end # I want all Enumerables to be able to Narf module Enumerable include Narf end # Fjord is an Enumerable defined *after* including Narf in Enumerable class Fjord include Enumerable end p Enumerable.ancestors # Notice that Narf *is* there p Fjord.ancestors # Notice that Narf *is* here too p Array.ancestors # But,grr,not here # => [Enumerable,Narf] # => [Fjord,Enumerable,Narf,Object,Kernel] # => [Array,Kernel] Fjord.new.narf? # And this will print fine Array.new.narf? # And this one will raise # => (from Fjord) ZORT! # => NoMethodError: undefined method `narf?' for []:Array