加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:C类包含模块M;包括M中的模块N不影响C.什么给出?

发布时间:2020-12-17 01:18:28 所属栏目:百科 来源:网络整理
导读:更详细地说,我有一个模块Narf,它为一系列类提供了基本功能.具体来说,我想影响继承Enumerable的所有类.所以我把Narf包含在Enumerable中. Array是一个默认包含Enumerable的类.然而,它并没有受到Narf在模块中的后期加入的影响. 有趣的是,在包含之后定义的类从En
更详细地说,我有一个模块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

解决方法

您会想到两个解决问题的方法.他们都不是真的很漂亮:

a)浏览包含Enumerable的所有类,并使它们也包括Narf.像这样的东西:

ObjectSpace.each(Module) do |m|
  m.send(:include,Narf) if m < Enumerable
end

这虽然很狡猾.

b)直接将功能添加到Enumerable而不是自己的模块.这可能实际上是可以的,它会起作用.这是我推荐的方法,虽然它也不完美.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读