簡體   English   中英

將模塊中定義的方法與Ruby中的類方法一起使用

[英]Using methods defined in a module with class methods in Ruby

我有一個小問題,我無法完全解決。 由於我想重用我的課堂中定義的許多方法,因此我決定將它們放入一個Helper中,可以在需要時輕松地將其包括在內。 基本類如下所示:

class MyClass
  include Helper::MyHelper
  def self.do_something input
    helper_method(input)
  end
end

這是助手:

  module Helper
    module MyHelper
      def helper_method input
        input.titleize
      end
    end
  end

現在,由於我認為范圍問題,我無法從我的班級中調用“ helper_method”? 我究竟做錯了什么?

我猜這是因為do_something input內部的self指針是InternshipInputFormatter ,而不是InternshipInputFormatter的實例。 因此,調用helper_method(input)適當別名將是self.helper_method(input) ,但是您已經將Helper::MyHelper作為實例方法(而不是單例self.helper_method(input) 包含InternshipInputFormatter類中,因此請嘗試使用實例方法擴展該類。作為該類的signelton方法的模塊:

class InternshipInputFormatter
   extend Helper::MyHelper
   def self.do_something input
      helper_method(input)
   end
end 

InternshipInputFormatter.do_something 1
# NoMethodError: undefined method `titleize' for 1:Fixnum

如您所見,該調用已停止了helper_method內部的執行。 請參考文檔以了解includeextend之間的詳細區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM