Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module_function_vs_private_methods
module MyModule
module_function
def module_foo
'module_functions are singleton_methods on a module, which allow explicit receiver'
end
end
class MyClass
private
def private_foo
"private instance methods cannot have an explicit receiver, and are not singleton_methods"
end
end
# module_functions can have an explicit receiver and they are singleton methods
MyModule.module_foo
# private instance methods can only be called on an instance of that class, without an explicit receiver
instance = MyClass.new
begin
instance.private_foo
rescue
"you cannot call a private method with an explicit receiver, that is with the '.'(DOT) syntax"
end
# you can however, do this to call a private method
instance.send(:private_foo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment