donovan.lampa
donovan.lampa

Reputation: 684

What's the difference between a module function, an instance method and a class method in ruby modules?

I'd like to know the specifics about how methods defined in a module are scoped when they're defined as module_functions, class methods (i.e. 'def self.foo') and instance methods (i.e. 'def foo')

How does the behavior change when including the module in to different classes if at all?

I've been digging around on the internet and haven't been able to find a good explanation.

Upvotes: 2

Views: 2181

Answers (1)

Chuck
Chuck

Reputation: 237010

A class (or more properly, module) method is defined on the module, and is called with the module as a receiver. It won't be mixed in when you include YourModule.

The instance methods of a module are mixed in as instance methods of the caller when you do include YourModule.

The module_function method takes an instance method you've defined in the module, makes it private (and it will remain private when mixed in), and also turns it into a public module method.

Upvotes: 3

Related Questions