2

所以我在 ruby​​ 中尝试 mixins 和一些元编程,但无法让它为我工作。我想让它打印“狒狒”

 module A

  def self.included(base)
      base.extend ClassMethods
  end

  module ClassMethods
    def install_A
        include InstanceMethods
    end
  end

  module InstanceMethods
      class B
         def testB
           #What goes here???
           A.monkey
         end
      end

      attr_accessor :monkey

      def initialize()
         @monkey = "baboon"
      end

      def test
          b = B.new
          puts b.testB
      end
  end
end

class Chimp
  include A
  install_A
end

c = Chimp.new
c.test
4

1 回答 1

4

B是它自己的自包含类。它不与任何其他类或模块相关联或连接,只是说一个类的实例B恰好是在InstanceMethods::test. 在定义内部声明class Bformodule InstanceMethods限制了B它在外部不可见的范围,InstanceMethods但它不以任何方式连接。BInstanceMethods

您需要的是使模块的变量在B. 您可以实现一个带有参数的initialize方法B,并InstanceMethods::test可以使用b = B.new(@monkey)将值传递给B(确保B::initialize将值存储为实例变量)。

于 2012-05-26T00:15:49.057 回答