What Are Modules?1:47 with Jason Seifer
In Ruby, a module is kind of like a Class or Object in that it is it’s own “thing”. Modules are used for a few different purposes: containers, behaviors, and occasionally storage.
[SOUND] Hi, I'm Jason, your Treehouse Ruby teacher. 0:00 In this course we're going to be going over modules in Ruby. 0:07 If you've been following along with other Treehouse Ruby courses 0:11 you've already come across and used modules, although you may not know it. 0:14 If you haven't, don't worry. 0:19 We'll be doing a little bit of a refresher about classes and 0:20 how they relate to modules. 0:24 The two share some very special similarities. 0:26 In Ruby, a module is kind of like a class or object in that it's its own thing. 0:29 Modules are used for a few different purposes, containers, 0:35 behaviors, and occasionally, storage. 0:39 One of the most common uses of modules in Ruby, is adding behavior to classes. 0:43 Let's take a game as an example. 0:49 If we're building a game that had robots that could shoot laser guns, and 0:52 as we're coding the game, we give the robots methods like LaserBlast, 0:56 LaserDamage, DrawLaser and more. 1:00 Later on, as the game design progresses, 1:03 we decide that we have a few more kinds of characters. 1:06 Like sharks that need to shoot lasers also because it's a crazy world out there, 1:09 and they were jealous of the robots. 1:13 We could take all of the methods from the robot class that have to deal with lasers 1:16 and put them into a module. 1:20 And we could call the module something like uses laser blaster, and 1:23 that's where we could keep all of that behavior. 1:27 If we were to include the, uses LaserBlaster module, 1:31 in the shark class, it would now have access to all of those methods. 1:34 When we do that, it's called using a module as a mix in, 1:39 because we're literally mixing in behavior to a class. 1:43
You need to sign up for Treehouse in order to download course files.Sign up