Can I invoke an instance method on a Ruby module without including it? Can I invoke an instance method on a Ruby module without including it? ruby ruby

Can I invoke an instance method on a Ruby module without including it?


I think the shortest way to do just throw-away single call (without altering existing modules or creating new ones) would be as follows:

Class.new.extend(UsefulThings).get_file


If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as

module Mods  def self.foo     puts "Mods.foo(self)"  endend

The module_function approach below will avoid breaking any classes which include all of Mods.

module Mods  def foo    puts "Mods.foo"  endendclass Includer  include ModsendIncluder.new.fooMods.module_eval do  module_function(:foo)  public :fooendIncluder.new.foo # this would break without public :foo aboveclass Thing  def bar    Mods.foo  endendThing.new.bar  

However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?

Edited to show that includes still work if public :foo is called after module_function :foo


Another way to do it if you "own" the module is to use module_function.

module UsefulThings  def a    puts "aaay"  end  module_function :a  def b    puts "beee"  endenddef test  UsefulThings.a  UsefulThings.b # Fails!  Not a module methodendtest