简体   繁体   English

在另一个类中使用模块的类

[英]using class of a module in another class

I'm creating a gem: 我正在创建一个宝石:

module Core
  require "lib/doctor"
  require "lib/slot"
end

module Core
  class Doctor
    def message
      puts Slot.message
    end
  end
end

module Core
  class Slot
    def message
      return "Hello World"
    end
  end
end

If I use the gem I obtain: 如果使用宝石,我将获得:

Gem Load Error is: uninitialized constant Core::Doctor::Slot

As you can see from your error, ruby is trying to load the constant Slot in the context of Core::Doctor . 从错误中可以看出,ruby尝试在Core::Doctor上下文中加载常量Slot But, you want Slot in the context of Core . 但是,您需要在Core上下文中使用Slot So, try: 因此,请尝试:

module Core
  class Doctor
    def message
      puts Core::Slot.message
    end
  end
end

Also, here: 也在这里:

puts Core::Slot.message

you're trying to call message as a class method. 您正在尝试将message作为类方法进行调用。 However, here: 但是,这里:

module Core
  class Slot
    def message
      return "Hello World"
    end
  end
end

you're defining message as an instance method. 您将message定义为实例方法。

If you want message to be a class method, you'll need to do: 如果要将message用作类方法,则需要执行以下操作:

module Core
  class Slot
    def self.message
      return "Hello World"
    end
  end
end

or 要么

module Core
  class Slot
    class << self
      def message
        return "Hello World"
      end
    end
  end
end

(depending on your preference). (取决于您的偏好)。 If you want keep message as an instance method, then you'll need to do: 如果您希望将message保留为实例方法,则需要执行以下操作:

puts Core::Slot.new.message

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM