Is it possible to call the function of the module inside the class, which is also located in this module

In this Ruby code:

Module M
  Class C < Struct.new(:param)
    def work
      M::helper(param)
    end
  end

  def helper(param)
    puts "hello #{param}"
  end
end

I get the "undefined" helper "method for the error" M: Module "when I try to run

c = M::C.new("world")
c.work

but calling M::helper("world")directly from another class works fine. Can classes not call module functions defined in the same module in which they are defined? Is there any way around this other than moving the class outside the module?

+5
source share
4 answers

To call M::helper, you need to define it as def self.helper; end For comparison, take a look at helper and helper2 in the following modified snippet

module M
  class C < Struct.new(:param)
    include M     # include module to get helper2 mixed in
    def work
      M::helper(param)
      helper2(param)
    end
  end

  def self.helper(param)
    puts "hello #{param}"
  end

  def helper2(param)
    puts "Mixed in hello #{param}"
  end
end

c = M::C.new("world")
c.work
+4
source

self:

module M
  class C < Struct.new(:param)
    def work
      M::helper(param)
    end
  end

  def self.helper(param)
    puts "hello #{param}"
  end
end
+3

C helper M, helper M singleton class. , , helper , . helper :

module M
  class C < Struct.new(:param)
    def work
      M::helper(param)
    end
  end

  module_function

  def helper(param)
    puts "hello #{param}"
  end
end

:

module M
  class C < Struct.new(:param)
    include M

    def work
      helper(param)
    end
  end

  def helper(param)
    puts "hello #{param}"
  end
end

helper M singleton module_function. M C, C . , M.helper . helper C . , helper private:

module M
  class C < Struct.new(:param)
    include M

    def work
      helper(param)
    end
  end

  private
  def helper(param)
    puts "hello #{param}"
  end
end
+2

:

ruby ​​docs.

. . , - . , , . (. Module # module_function.)

self.methodname .

, M::helper, M.helper, ++. - ( ruby ​​builtin) .


- , (+ ). Module object, Class object .

Module ( Class) ( ). (Module/Class/instance) .

, , including - .

, :

module MM
  def helper(param)
    puts "hello #{param}"
  end

  class ReceiverClass
    include MM           # add helper() to ReceiverClass
  end

  class C < Struct.new(:param)
    def work
      ReceiverClass.new.helper(param)
    end
  end
end

c = MM::C.new("world")
c.work
+1

All Articles