Introduction to Blocks with the .times Method in Ruby

Boris Paskhaver
A free video tutorial from Boris Paskhaver
Software Engineer | Consultant | Author
4.7 instructor rating • 6 courses • 292,691 students

Lecture description

  • Call the .times method on an integer to repeat a certain operation that number of times.
  • Introduce the concept of blocks, an attachment to a method call that modifies its functionality

Learn more from the full course

Learn to Code with Ruby

A comprehensive introduction to coding with the Ruby programming language. Complete beginners welcome!

31:25:46 of on-demand video • Updated September 2020

  • Learn to program in the Ruby programming language
  • Master common Ruby objects like Strings, Arrays, Hashes, and more
  • Solve popular coding challenges and algorithms with Ruby
  • Dive into object-oriented programming including classes and more
English [Auto] Are right in this lesson I wanted to offer a quick introduction to blocks in Ruby a ruby block is a grouped collection of Ruby statements that immediately follows a method call. So a block is one of the few exceptions to the general rule that everything in Ruby is an object. A block is not an object. It's sort of like an add on to a method call that clarifies how that method should operate in regards to a specific detail. So a block cannot exist except for within the context of a method. So blocks add a little bit of clarity. Whenever a method it requires a little bit more detail. Now this can be a fairly difficult concept the first time you see it. So rest comfortably as we proceed throughout the course we're going to have plenty of practice with blocks. The purpose of this lesson is to give you a general idea of how they function and what purpose they serve. We're going to dive into them in much greater detail as we proceed. And as we get more practice with them. So again a block is not the same thing as a method. A method is a message that we send to an object but a block is attached to a method call to an object. For example let's say I have a Fixnum object here like five five is a basic integer a number a whole number the fixed number includes a available method called Times. Right. Just like any other method like next except this method is called Times. And what this method does predictively is execute a certain process a certain number of times whatever the actual number or object that the message or method is called. So if we call the times method on 5 We're going to do some kind of process five times over if instead we call it on a fixed number like 10. That means execute a specific process ten times over. Right. But how do we actually clarify or tell Ruby what it is that we want to do a certain number of times. That's precisely what the block does in this specific method call. So how the block operates and what it does is going to depend on what the method is. In this case when we're dealing with the times method it's going to specify what we do that number of times. In this case what we want to execute ten times over. There are two syntactical ways that we could write a block one with curly braces and one with two keywords called do an end and I'm going to introduce both of them right here. Let's begin with curly braces. I'm going to open up a pair of curly braces right here. Those are those little squiggly ones. And as soon as you write the first Adam is automatically going to fill in the second 1:42 and everything that I write in here between my curly braces represents the body of my block. So here I write what I want to do in this case 10 times over. So I'm going to write puts And let's say Borris is awesome. All right. So this part began with the curly braces and everything inside it is the block the block is attached to a method called. It is not the same thing as an argument right but it is attached to a method call and it clarifies how this method is going to operate. And what are we going to do 10 times over. We're going to put out the string. Boris is awesome. When execute this you can see that Boris is awesome is going to be output 10 times over. If I change this number up front or something else like a different them like three or predictively Predictably this is going to happen three times now instead of 10. But the block's content remains the same. So it's simply going to repeat that code puts Borris is awesome three times over. Let me go ahead and comment this line of code and we're going to repeat it using the alternate form the alternate syntax rather for creating a block. I'm going to do the exact same thing three times three is my Fixnum object. Times is the method that I call it and what I provide after is called the block up top here we have our very first option with curly braces. Our second one is with the keywords do an end and the traditional syntax for doing this is to write do immediately after the method call. Skip a few lines and then right and right here. Now that General best practice is to stick with curly braces whenever we have a one line block so in this case we only have one line that we want to execute. So we were able to structure everything within one line and thus we use curly braces do and is designed to be used whenever you have more than one line of code that you want to execute within each block. So in this case we're specifying what we want to do three times over. So let me put multiple lines in here. I'm going to puts Borris is incredible and right below that I'm going to puts I'm having so much fun learning Ruby. So here we have a body of the block that is two commands long or two statements long. So he's satisfied that best practice of having a body here between do and end that is more than one line long. Now this is just a best practice right so you can have a do and with only one line of code. And similarly you can have curly braces with multiple lines of code between them. But the best practice is to stick with this design of curly braces for one line do and for multiple lines. Otherwise this is still a block. So everything here between the beginning of do and the conclusion of and is a block and this is what we're going to execute three times over outputting these two strings right after the other. So when execute three times over we're going to output Borris is incredible. And having so much fun learning Ruby you can see it repeated right here in the atom and output. Now this is where it gets kind of tricky because blocks can also include something called the block variables. The blocks block variables is a temporary variable. That's going to represent something within the context of that block's execution. And here's how we create a block variable. We do it in between vertical pipes. So here I'm going to add two vertical pipes. This is the syntax right. And in here I'm going to specify a block variable. Now depending on what method it is that you're calling what the block variable or block of variables represent is going to change in the context of the times method. What we provide to the block variable is going to represent the number of the iteration. So for example I could write something like count right here in between my vertical pipes here. Now this thing in here the block variable can be whatever name we want we can call this count we can call this I we can call this iteration we can call it Vora as a basically any name that you want to provide is fine here as long as you're not using some kind of default Ruby keyword. OK so in here I'm just going to stick with count right and count as you can see from the fact that we ran this a few moments ago without it is optional so we don't have to actually use it. But in this case we can and we provide it within the vertical pipes and now we have access to that block variable in the context of the execution of our block. So what I can do here is put this puts we are currently on loop number and interpolate the current value of the count block variable. Now Ruby in this case is actually going to start counting at zero. So our count is going to be 0 1 and 2. In order to make this work three times over. So when I execute this I'm going to get. We are currently on loop number zero. The count begins at zero and then we're going to repeat the two lines below. And then it's going to begin again executing the entire content content of the block's body. And then we're going to get to we are currently on loop number one followed by we are currently on loop number two. Now just to prove to you that our block variable name can be anything that we want. I can replace this with something like I replace this with I as well. And you can see here no problem. Right so this is just our own name that we're assigning and what it represents is going to depend on what method that block is being attached to within the context of the times method. It represents the current iteration keeping in mind that that iteration starts counting at zero. OK not at one. Another thing to watch out for here is the block variable is only going to exist locally within the blocks execution. So if I tried to output I after run done iterating it's going to be trigger an error I is not going to exist except for within this block when it's working with iterating and representing the the current count. If I try to output I after I'm going to get undefined local variable or method I because I is not going to exist at this point on line 9 it's only going to exist temporarily during the context of execution of this block. So block variables are designed to be temporary. There is simply to be used for the execution of each block. Now if I wanted for example to have this running count start at 1 I can do something like this. I can simply add I plus 1 and get rid of this put statement of ID because I am not going to exist in this case. You can see we're going to get the same result except except that's going to say we are currently on loop number one followed by two and three. That's just a different way of representing it. But again what the block variable represents is simply the current number or count of the iteration. The process is exactly the same if we use curly braces. So right here I'm going to comment out my code between lines 3 and 7 and going to uncomment my code right here. And in this case if we're using curly braces for a one line block I simply put the block variable after my opening curly brace so in here I can do something like this count as the name of my block variable in vertical pipes after my opening curly brace. Here I write what I want to do in this case I'm not actually utilizing count so it's kind of pointless so let's do something like we are on number count. I'm going to interpret that block variable and here you can see we're going to get we are a number 0 we are number one and we are number two. So again count the block variable as representing the same thing. This is just to prove to you that block braces versus blocks with the do and don't make any difference it's just a syntactical difference it's a variation but they both function the exact same way. And just like with do and if I try to output count afterwards I'm going to get an error because Count is a local variable. It's a block variable that is only limited to this execution. As soon as the block is done it ceases to exist entirely. OK so this has been a very quick introduction to blocks. Hopefully you are getting that general big picture overview. I know the syntax will take a little bit of time to get used to. So here's what I recommend. Copy your code or copy the current code that you have right here in common and out. Because I'm going to clear mine and I'm going to offer you a challenge right here. When you go ahead and clear my code the challenge is this use the times method to output the first 10 multiples of three. What that means is the number is 3 6 9 12 and so on all the way until we get to 30. OK. Remember that the first loop is going to start at zero. When you use a block variable you have to add one to each to each block variable as you proceed through the iteration. But otherwise the process is going to be the same it be clever. Take a second to pause the video and see if you can figure out how you can output the first 10 multiples of three starting from 3 using something like The Times method and the attachment of a block with a block variable. I'll see you in a few seconds. OK here's how I solve this problem. Keep in mind that you can use either you and your colleague Brace's whatever you did is totally fine as long as it works. In this case I'm going to use do an end because I'm going to make a couple of lines here. So let's say I begin with the number 10 that's my Fixnum object. It has an available times method that method accepts a block. So I'm going to create a block with do an end and of course the alternative here is curly braces on a single line. This is exactly the same thing. There is no technical difference it's only a syntactical difference between those two. After do I'm going to write my vertical pipes to specify that I'm going to give a variable name to my block variable which is only going to exist within the execution of the Block. And this time let's say I do something like count. Keeping in mind that count will start at zero. So I have to remember that. And what do I want to do. I want to say All right let's show the next multiple. Of course this is not required. This is just because I have do and and and I want to write an extra line here to make this a proper multi-line block and here's where I can actually output it. So here's what I can do I can do puts And in here what I can do is interpolate three times whatever the current count is. But keep in mind if I do this if I do this currently Let's take a look at what's going to happen. We're going to have something very close but we're going to start counting at zero here you can see because Count start to zero. It proceeds all the way to 9 0 1 2 all the way to 9 which is technically 10 iterations right. But in our case it's going to give us 0 through 27 instead of 3 through 30. So what I can do here to make this work is to add plus one here and to prevent the operation from first multiplying before it adds what I want to do is this. Wrap this in parentheses that way. Count is going to start at zero it's going to have one added to it to get one then multiplied by three to get three. And then so on and so forth it's going to repeat the process starting at three then six then nine as count increments by one every iteration until we get to 30 which is going to be 10 iterations. So here you can see we're getting. All right. Let's show the next multiple 3 6 9 12 and so on. If I wanted to do this with a simple curly brace I can do it like this ten times do rather not do. But curly braces count I'm going to copy this code right here because that's the only one I need. There we go. I'm going to comment on this code so we don't get confused about what's doing what saved us run. And you can see we're getting the exact same result. It's outputting the first 10 multiples of 3 except we're using the curly brace and Tex here to create a block. So again to iterate curly braces versus do and no difference. Technically two ways to accomplish the exact same thing to create a block within the block. We can spot we can specify an optional block variable that's written in between vertical pipes that specifies something that's going to change on every single iteration. Blocks are specifically designed to be attached to method calls. So this thing right here the block cannot live by itself. It can only live within the context of a method execution. In this case the method that the block is attached to is times times is called on a number or an integer and it does something that a number of times what it does is what we specify in the actual block itself. So I block is sort of like an addendum. It adds a little bit of an add on. That clarifies how the method is supposed to run. Cause the times method fundamentally says do something this number of times but what does that additional clarity that additional clarification that additional specification of what the actual process is is what we provide in the block. Again between either curly braces or do and so that's a very quick introduction to Bloch's we're going to see a bit more or a few more examples in the upcoming lessons but hopefully this will give you a general sense of what purpose they serve. The syntax again will take a little bit of time to get used to. I'll see you in the next lesson.