Build a Monster Class: Part 42:49 with Jason Seifer
In this stage, we'll be working towards creating our own class that uses blocks, arrays, hashes, and more. In this video, we'll learn a neat trick about yielding to blocks.
The following code will return the current object in context to a block:
yield self if block_given?
This is useful in cases where you would like to have access to the class inside of a block.
So we're done with our Monster program, 0:00 but I wanted to show you something really cool that you can do with blocks. 0:02 So, here we have our different actions and 0:07 we're calling them within the context of a block. 0:13 Let's just see what the last thing that we have here, okay, monster.hide. 0:16 Let's go to this hide method, and we yield to the block, 0:20 which means we're coming out of this method, and calling that block. 0:25 So, it jumps from here, in this hide method, 0:30 down to monster.hide, right here, and executes this block of code. 0:34 Something that's kind of neat that we can do is yield arguments to the block. 0:42 Now we know that from earlier lessons that we can provide arguments to the block. 0:48 So, we'll just say if a block is given here, 0:54 let's provide this argument and what argument would that be? 0:59 Well, if wanted to we could provide the actions variable and 1:04 then we would have access to that in the block, but 1:08 let's do something a little more interesting and yield self. 1:12 Self is the instance of the monster. 1:18 So we'll get the monster instance inside of the block. 1:23 Which means. 1:26 We could put this in as an argument called monster. 1:33 And in here, we would have access to the monster variable. 1:38 And actually, let's just put that in as m. 1:43 And let's print out the actions here, just to see what it looks like. 1:47 Printed out the scoreboard. 1:58 Let's go back up. 1:59 And this is pretty neat right here, screams, scares, runs, and hides. 2:01 And let's go ahead and just prove that we can get access to all the methods in here. 2:07 We define an inspect method. 2:13 We'll just say inspect is the name and the actions. 2:19 Clear my screen. 2:32 Run this one more time. 2:33 And here we go, 2:36 we've implemented an inspect method that we call from inside of this block. 2:37 This is not something you totally need to do, but it is pretty cool and 2:43 something that you will see in Ruby programs. 2:46
You need to sign up for Treehouse in order to download course files.Sign up