简体   繁体   中英

Ruby: Use module method inside a class method

How do we use a module method inside a class method without extending the module?

module TestModule
  def module_method
    "module"
  end
end

class TestClass
  include TestModule

  def self.testSelfMethod
    str = module_method
    puts str
  end
  TestClass.testSelfMethod
end

Then it returns:

test.rb:11:in `testSelfMethod': undefined local variable or method `module_method' for TestClass:Class (NameError)

By including the module, you make module_method is an instance method on TestClass , meaning you need to invoke it on an instance of the class, not the class itself.

If you want to make it a method on the class itself, you need to extend TestModule , not include it.

module TestModule
  def module_method
    "module"
  end
end

class TestClass
  extend TestModule # extend, not include

  def self.testSelfMethod
    str = module_method
    puts str
  end
  TestClass.testSelfMethod # "method"
end

Just because comments are too few characters, but agree with maegar :

module TestModule
  def module_method
    "module"
  end
end

class TestClass

  def self.testSelfMethod
    str = module_method + " from class"
    puts str
  end

  def testSelfMethod
    str = module_method + " from instance"
    puts str
  end
end

TestClass.extend TestModule
TestClass.testSelfMethod # => module from class

TestClass.include TestModule
TestClass.new.testSelfMethod # => module from instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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