Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Modules Include and Extend Include

Can I use instead of the module, a class? And can I do the same when creating a separate class out of this Fetcher class

Hi, can I do the following?


class Fetcher def fetch(item) ... end

end

class Dog include Fetcher

atr_reader :name def initialize(name) @name = name end

end

dog = Dog.new("Bela")

dog.fetch("Test message")

If so, why to use a module instead? Also can I create the class Fetcher as a separate class and just include it into the class Dog/Cat?

Thank you, Miroslav

1 Answer

Garrett Carver
Garrett Carver
14,681 Points

Hi Miroslav, You can think of classes as objects (Dog, Cat, ect), and modules as abilities that can be shared between those objects. Someone answered this on stack overflow a bit better than me:

"A class should be used for functionality that will require instantiation or that needs to keep track of state. A module can be used either as a way to mix functionality into multiple classes, or as a way to provide one-off features that don't need to be instantiated or to keep track of state. A class method could also be used for the latter.

With that in mind, I think the distinction lies in whether or not you really need a class. A class method seems more appropriate when you have an existing class that needs some singleton functionality. If what you're making consists only of singleton methods, it makes more sense to implement it as a module and access it through the module directly."