【问题标题】:Ruby: How to call an instance method of a Class from a Module?Ruby:如何从模块中调用类的实例方法?
【发布时间】:2012-11-25 00:01:38
【问题描述】:

我在一个类上定义了一个实例方法:

class Foo
  def is_linux
    # some code...
    # returns true or false
  end
end

我想在一个模块中调用这个方法:

class Foo
  module Dog
    is_linux? ? puts "Is Linux" : puts "Is Windows"
  end
end

这给了我以下错误:

NoMethodError: undefined method `is_linux?' for Foo::Foo:Module

我知道我会写

class Foo
  module Dog
    Foo.new.is_linux? ? puts "Is Linux" : puts "Is Windows"
  end
end

但我想知道模块是否有办法访问当前实例?

【问题讨论】:

    标签: ruby methods instance


    【解决方案1】:

    基本上,您需要以某种方式“共享”您的实用程序方法。

    我建议将它们放入 mixin:

    module Mixin
      def is_linux?
        true
      end
    end
    
    class Foo
      include Mixin # adding methods at instance level
    end
    
    class Foo
      module Dog
    
        extend Mixin # adding methods at class level
    
        puts is_linux? ? "Is Linux" : "Is Windows"
    
      end
    end
    
    #=> Is Linux
    

    【讨论】:

      【解决方案2】:

      没有这样的选项,因为子类型(如模块)没有与其父实例连接。如果您需要这样的构造,您只能制作is_linux? 类方法。如果没有这种可能性,那么可能是您的设计错误。

      【讨论】:

        猜你喜欢
        • 2011-02-01
        • 2010-09-30
        • 2015-10-26
        • 1970-01-01
        • 2012-06-23
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 2014-03-22
        相关资源
        最近更新 更多