1

I have troubles with understanding the global area of visibility in Ruby, so, I know that you cant use Module methods in your own class for example:

module Mod
   def self.meth
      “module method”
   end
end

class Klass
   include Mod
end

p Klass.meth

# Error

but when i knew that you can do such thing:

include Math

p sin 2
#0.909....

I was confused, because i thought you cant use module methods in any class without calling the method name. Also i had a supposition, that module Math has instance methods, like Kernel, but, unfortunately, no. Now i am doubting, that I understood such methods like extend and include correctly, so, could you please explain to me this thing and what will happen if we will change include to extend

1 Answer 1

1

You have encounter a weirdness of module_function: https://apidock.com/ruby/Module/module_function/

module Foo
  def foo # this is (irb) 2
  end
end

Foo.singleton_methods #=> []
Foo.instance_methods #=> [:foo]
Foo.instance_method(:foo).source_location #=> ["(irb)", 2]

module Foo
  module_function :foo # this is (irb) 9
end

Foo.singleton_methods #=> [:foo]
Foo.singleton_method(:foo).source_location #=> ["(irb)", 2]
Foo.instance_methods #=> []
Foo.private_instance_methods #=> [:foo]
Foo.instance_method(:foo).source_location #=> ["(irb)", 2]

So, module_function takes an instance method of the module, makes it private and copies it onto a singleton class.

module_function can also be used without the method name, which works a bit like private method, modifying all the future methods added to this module.

Math is a full module_function module, meaning that the methods are defined both as singletons and private instance methods, which is why you can use it both ways.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. Talking about why module#instance_methods doesn’t show foo, that is why module_function defines method foo as private.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.