Sign In | Subscribe

Enter your Sign on user name and password.

Forgot password?
  • Follow us on:
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to Ruby
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!


  • This course goes over Ruby's extensive collection of loops: while and until, for and in, iterators, and enumerables
  • while-loop executes while a certain condition is true
  • until-loop executes until the condition becomes true
  • do-while-loop executes body first and continues while a certain condition is true
  • keyword break allows you to stop the execution of a loop
  • Integer has three commonly used iterators: upto, downto, and times
  • External iterators use the Enumerator object
  • RDoc:
  • Enumerable is a mix-in allowing several traversal and searching methods for classes
  • RDoc:
  • Array, Hash, and Range are commonly used enumerable objects
  • collect, select, reject, and inject are commonly used iterators.


Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Loops 0:12
    • while and until
    • for and in
    • iterators
    • enumerable in objects
  • While-loop 1:14
    • Will keep going is condition is true
  • Until-loop 2:58
    • Will keep going until condition becomes true
  • Single Expression Loops 4:20
    • Compact form
    • Expressed as a modifier
  • Do-While Loop 5:52
    • Executes body first
  • Do-Until Loop 7:54
    • Similar to do-while loop
    • Using Break Inside Loops
    • break
  • For-In Loop 11:56
    • for-loop
    • var
    • collection
    • body
    • Examples
    • Examples (Cont.)
    • Nested loops
  • Numeric Iterators 18:32
    • upto
    • downto
    • times
    • Examples
  • External Iterators 21:00
    • Enumerator class
    • Rdoc
  • Enumerables in Objects 24:35
    • Enumerable is a mix-in
    • RDoc
  • Commonly Used Enumerables in Objects 27:01
    • Array
    • Hash
    • Range
    • Examples
  • Enumerables in Objects (Cont.) 31:13
    • File Processing
    • Example
  • Enumerables in Objects (Cont.) 33:07
    • collect
    • select
    • reject
    • inject

Transcription: Loops

Welcome back to

Today's lesson is on Ruby loops.0001

Ruby has quite an extensive collection of loops.0009

When you are working with Ruby, there are many different ways you can do your coding--it's very flexible--and in the same sense, there are many different types of loops you can be using.0016

That's why I say, in this next one: You have the flexibility to choose the one that is best for you.0032

We are going to go over the four different types.0039

The first two are real loops: the while and the until loop.0046

Next, we will look at the loop, and then we will look at more loops that you will see in objects.0053

We are going to do this through iterators and enumerables and objects.0062

The first one we are looking at is the while loop.0071

The while loop has code that executes while a certain condition is true.0075

This while loop will keep going if this condition holds true.0086

For this example, we have the items=0, and we have a loop that says, "While the items is less than 10, do the things in this code block."0090

Here is the code block.0107

It says, "I want you to print out the number of items that it puts"--so that is a new line--and then it says, "Increment the number of items by 1."0114

When this first gets in this loop, it is going to print the value 0, it's going to increment items, and then it's going to go back to this check that says, "Items less than ten?"--and if it is, then it's going to say, "OK, we're going to go back in the loop."0125

So, it's going to say 0,1,2,3,4,5,6, all the way down; the question is, when it hits this mark here: at the 9 value, it's going to print that out.0144

But the last one is going to increment to 10, and that is going to hold false.0162

So that is where it is going to stop.0167

It's going to print 0 to 9.0169

The next one we will look at is the until loop.0176

The until loop says, "Until this condition becomes true..." so that means, while it's not true, it's going to continue doing it.0179

It's interesting, because most other languages, you won't see an until loop; so this is kind of a special one that is in Ruby.0193

Here we have items=0, and this loop says, "Until items is greater than or equal to ten, continue doing these things."0203

It says, in this case, that I want to print out the items and then increment the items by 1.0212

This is just like the while loop, but we are using the until loop for this.0220

Notice also, our check here has changed, so this is going to print out the value 0, print out the value 1, 2...and once this items equals 10, it is going to stop.0226

Again, it's going to go all the way down to value 9, and it's going to have the exact same code as the while loop, but we are using the until loop for this case.0243

The next thing we're going to look at is single expression loops.0258

This is a very compact form--usually you see single expression loops as a kind of one-liner loop.0262

It is expressed as a modifier.0275

When I say "modifier"--you have your while here--and for example, let's say x=0.0281

What I'm going to say here is, "I want you to print out x=x+1 while x is less than 5."0292

Notice, it's all in one line; so, it's going to continue doing this while x is less than 5, and then once it hits this condition, then that is going to end that line.0307

Notice, the end result is x=5.0322

Again, I'm going to do that with an until loop--I'm going to use y=10, and it says, "Until y=1, continue to decrement that y value 1 by 1."0326

Once it hits 0, it will hit this condition, and the until loop will say, "I'm going to stop now"--when this y is equal to 0.0338

The next one we're going to look at is the do while loop.0351

What this does is...first, the body will execute: the body executes before it checks the condition.0354

The second is not followed as a Ruby convention...there really isn't a do while loop in Ruby, so we are kind of using that flexibility to create our own.0364

It's useful if you are adjusting to Ruby from another language, which...many people use do while loops in Java, C, it might be common to use it this way, too, because it's more familiar to you.0376

So, for example, we have this x=10; we have this begin loop that says, "Hey, I'm going to take this x value and decrement it by 1."0389

It's going to end, because it's also going to say, "While x > 10" you notice, for this one, the end result is 9.0399

What happens is, you get this value 10, and it gets decremented to 9, and then it goes in this while loop, and it says, "OK, 9 is not greater than 10, so I'm going to stop there."0413

Another interesting thing you can do is use parentheses.0426

With parentheses, the condition actually executes before the body.0431

Let's take that exact same example.0436

If I take x=10...I have my parentheses here; inside, there is a block that will decrement the value of x to 9.0439

It goes down by 1; but my condition is "while x > 10".0451

Now, since, with these parentheses, the condition executes before the body, the end result will still be x=10.0455

It never actually runs the block in there.0463

The next one we are going to look at is the do until loop.0470

This is very similar to the do while loop.0474

For this one, we are going to make a countdown; once it hits 0, it goes "Boom!"0477

So, I have my countdown=100; again, I'm using the begin/end; this is my block of code; and it's going to print 100, decrement it by 1, and check this condition.0483

This will have the value 100, all the way to 1, and then it's going to say, "Boom!"0505

Notice, here it says, "Once the countdown=0, don't run that code again," so it does not print out 00518

1 is the last one, and then it prints "Boom!" there.0525

Let's look at using the break inside the loops.0530

This keyword 'break' allows you to stop the execution of the loop.0535

I have this countdown, and it's equal to this huge number here.0543

While the countdown > 0...what we're going to do is say, "If this countdown class is equal to Bignum,"'s going to say, "Oh, this number is too huge; it is going to take forever to count down to 0."0552

So, I'm going to say "Abort it, and break out"'s going to break out of the while loop.0566

This break here allows you to stop the execution of the loop.0572

After that, if that case doesn't exist with this countdown, it's going to go ahead and decrement that countdown, one by one.0580

In this case, this is actually going to run.0591

Here is another example.0603

In this one, we are taking an Array, and we are going to break out that loop if it's not a fruit.0606

In this case, we are going to do a check, since we have this Array here: let's say a carrot came up--that's a vegetable, so we are going to abort out of this loop.0613

We are doing this until loop here, so first we check, "Hey, is the 'fruits' already empty?"--if it's empty, we're going to stop it.0622

First, we pop one fruit out.0636

If that fruit is equal to a carrot, then we are going to say, "Abort it: carrot is not a fruit."0640

What you will see with this is, it's going to first print out the's going to pop that out, I mean; so part of this 'fruit' is going to be popped out--so this is popped out.0648

Then, it's going to pop out the banana.0666

Then, it's going to get to this 'carrot', and it says, "Hey, wait: I can't work with this--this isn't a fruit."0674

It does this check, and it's going to abort and say it's not a valid fruit.0680

Now, because we actually had it pop is still going to call this pop command, so it's going to be carrot here...and then it's going to say that it's aborting.0685

"Carrot is not a fruit."0703

That is how we use break for that.0709

Now, let's look at the loop.0715

This is also known as the for loop.0722

Here is the structure of it: You have this for value; it has this var, and that is the value in the collection; and then you have your body of the code.0728

Now, what is var? Var is a variable or a comma-separated list of variables--we will go over that.0744

Collection is an object that contains an 'each' iteration method.0755

So, this object that is the collection itself has to have an 'each' method in there so it can do this for loop process.0763

Body is the code inside the for loop.0775

Here is an example we have: for the first one, we have a numbers array, 1 through 9.0785

Notice, what is our var? That is the i; our collection is this numbers, and this is our body--the puts i.0794

Notice what it is doing here for this loop; it's going to just print 1 to 9.0812

With this, this i is this value 1, and then it will be this value 2, and what it will do is, it will go through each one of these, one by one, until it gets to the end; then it prints all the values out.0822

Again, you can do this with a range, too; range is an object that has an each method, so you can do the exact same thing.0846

It's going to print the exact same output with this.0852

For this third example here, I want to show you that you don't even need to use the do declaration.0857

Notice, here I just do for i in 1..9, and it's still going to output the same value.0865

Now, for this last example here, I have this numbers=1...this hash: numbers, 1, has a value of 1; this key 2 has a value of 2; key 3 has a value of 3.0874

What is interesting here is, notice, the var actually is a comma-separated list now.0895

The var here is actually k,v.0901

Our collection is this numbers hash.0910

It's using the hash each method, so it says, "Hey, for this each method, I'm allowed to put in two arguments," so it says, "I'm going to put k is v and a dot."0914

So, for this one, it's going to say, for the will say 1 is 1, 2 is 2, 3 is 3.0926

An example here...I can show you a live example.0946

Let's do the numbers equals...1 is 1, 2 is 2, 3 equals 3.0958

We have our hash; now I'm going to create my loop.0969

For k in numbers plus k is v...end.0975

I have that same output here: 1 is 1, 2 is 2, 3 is 3.0987

Next, we are going to look at a nested loop.0997

With your loops, you can do nested loops: what is a nested loop?1002

It's this example here; what it does first is, it looks at this value i.1005

The first one will be 1.1015

And, in this loop, then, it's going to go through this j loop.1018

It's going to go ten iterations in, and then it's going to go back to the i loop, and then it's going to work with 2,3,4,5,6,7,8,9,10.1021

This is best with an example, so let me show that to you.1033

Let's go ahead and clear this out.1038

I'm going to just put the exact same loop here.1041

We are using the range for i, and 1 to 10 for j, and 1 to 10...and I'm going to just do print i.2s--take that integer value and convert it to a string...1045

Notice that we get this huge table of values because we're running this nested loop.1079

This first value is the i value, and the second one is the j one, and the output goes all the way down.1091

That is our nested loop.1102

Next, we are going to look at numeric iterators.1112

The Integer has three commonly used iterators: upto, downto, and times.1116

There are other iterators, but we are just going to look at these popular ones.1126

The first one is this example: it's 1.upto(5), and it's really self-explanatory.1130

The upto will increment by one.1136

For this example, it's going to output 1,2,3,4, and the last one, 5.1146

Now, let's look at the downto; the downto one says, "This is 10, and I'm going down to 1."1156

This is going to decrement the value by one.1164

This is going to go 10,9,...all the way down to 1; that is where it's going to stop.1172

The last one is this times method.1179

It's interesting, because with this times, you can actually see the same thing you did with I call this 10.times with this block--it's similar to 0.upto(n-1).1185

This would be like 0.upto(9).1205

We can see that in action.1218

I do 10.times...notice that the output here is 0 to 9.1223

That is the output that is printed out.1251

The next thing we are going to look at is external iterators.1258

This uses the Enumerator class; let's take a look at that.1264

This is the Enumerable class; this is not the same is the Enumerator class here; we can specify...the Enumerable class will get to that, but let's just change that for now.1274

The Enumerator class allows both internal and external iteration.1305

"An Enumerator can be created by the following methods"--there are Kernel methods here.1320

These methods "have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator wrapping the iteration."1329

The main ones we want to know are the each you will notice there is an each method, and this allow external iteration, so I can put the,,, and every time I do next, it outputs a value.1344

The next thing I want to show you is this peek_values and rewind.1368

As you create this iteration, you can see the values that are next.1376

First, you have this peek, so I can say, "Hey, I want you to tell me what will be next in this Enumerator value."1385

I can use this peek, and under peek, see, it's going to say that it's 1.1395

Peek--that is 2, and then I can go to the next, and I can do a peek again to check.1400

You can also do peek_values just to see how far you are in the enumeration.1407

First, let's look at one external iterator.1414

We are using the downto, but this time, we're storing it in a value.1421

I call this countdown method, equals 10.downto(1) when I do the output, I do countdown, next, and the first one is 10; I call it again, countdown, next, the next one is 9; and again--it's 8; and I can go down all the way with that.1427

Here is another external iterator; this one is just using each.1451

I can just do; it refers to this value here--the first next; the second one refers to this value, and the third one returns with that.1456

It returns the elements one by one through the iterator.1466

The next one we are going to go through is Enumerables.1473

What is an Enumerable? An Enumerable is a mixin that allows several traversal and search methods for classes.1475

It has built-in internal iterators, so you don't have to create your own.1486

Again, for this class, you have to define this each method; it's very important to using this mixin called Enumerable.1501

These mixins--you can just include them in the class you want them in, and then you have these cool traversal and search features as part of it.1509

Let's take a look at the RDoc.1518

Now we can look at our Enumerable class, here.1520

You can see it's a mixin, it provides classes for these traversal methods...I'll give you an example of what it does.1525

For example, here--look at this one--this [ant bear cat].1536

You can call this .all? method, and you can return a block.1545

And this block--you can say, "Hey, do all these words have a length greater than or equal to three?"1549

Using this, it will do the iteration for you, and it will say, "If that's true, I'll return true."1555

But, on this next example, it says, "Hey, are all of them the length 4?"1561

Since they are not all 4--only bear has 4 letters--then it's going to return false.1564

This Enumerable class allows you all these cool little methods that allow you to do these things, and they are all common methods you could be using, but you don't have to create your own; it's already built in.1571

Another one is this 'any'.1586

You can pass a block into it, and say, "Are there any words that have more than three letters?" or "...four letters?", and it returns true.1588

If you go through here, you will see that there are a lot of different examples.1599

We're going to look at more of this collect, and you will notice there are a lot of we're going through some of the more common ones.1605

OK, so the common ones we are going to look at for the Enumerable objects are this Array, the Hash, and the Range.1622

First, we are going to go over Arrays.1634

First, we are going to look at the each method.1639

I have my Array: it has three elements: 1,2,3; I call the each method, and it is going to put them out, one by one.1643

That is from the Enumerable class; it allows us to do that; it's 1,2,3.1656

Next, we have our Hash; again, we have our each method, and again, it's very similar to what we were doing before with the for loop, but now we have a different way.1662

Again, they have the same output: 1 is 1, 2 is 2, 3 is 3.1680

The last one is interesting: we have this each_with_index.1687

Now, when I call this each_with_index, it will pass me this element, plus it will pass me the index value.1693

So, for this one, it will get me the 1 with the 1, 2 is 2, 3 is 3, and I can inspect it and take a look at that.1706

It gives me parts of the Hash.1721

The Range: again you can do it with Ranges, also.1725

Notice how the output is all the same, but we are doing it with different objects, and it is giving us the same one.1731

This is 1,2,3,...we're all incrementing by one.1735

Here is how the each_with_index works--it hopefully clarifies what you just saw on the other slide.1740

First, it does take arguments, and it takes object.i, index, and then you take your block of code.1746

It calls this blick with two arguments, the item and the index.1759

Let's go through an example, so it may clear it up some more.1765

We're just going to use that example we were talking about--that numbers 1,1--key is 1, our value is 1--same with 2 and 2, key is 2--3 is the key, and the value is 3.1770

OK, we have our Hash, and let's create the each_with_index now.1792

We have our block, item and index, and then we're going to output this.1804

First, I want to output the actual parts of this Hash that we're doing: so we have our item, and then we're going to show you the index value it gets.1812

Notice, the Hash elements--one by one, they are actually converted to Arrays.1832

This object is an Array of key and value; then, in that same loop, it says this is the value 0.1837

On the second one--we're going to our second part, which is 2, our value 2, that index value 1; and it goes to our third one, which is Array 3,3, and our index value is 2.1847

That is the Enumerables.1866

Now, let's look at another example of file processing.1871

With file processing, you have this each method; it's used for the lines of code in the file.1874

This example we have is example.txt.1885

This file, can open the file, and then you can print out line-by-line, using this each method.1890

Let's see that in action.1900

I have an example here: I have some lorem ipsum text.1905

You will notice that it's a ton of text.1910

There are four paragraphs total.1914

What I want to do is output that.1918

I run my IRB, and then I'm going to just say the name of this file, and I'm going to do, so it's going to open the file, and then it's going to create a block for that.1922

I'm going to use that each, so it's going to use that Enumerable, but notice, this file defines each its own special way, and it's going to handle them, so it's going to be line-by-line.1939

I create a block called line, and I can declare it there, and one by one, each line is outputted to the screen.1950

So it's just like we opened that text file; it has all the text here, too.1964

I know it's a lot of text--a little overwhelming--but you can see it all there.1969

So we have that; let's look at some common iterators and Enumerables.1983

Let's look at collect, select, reject, and inject.1990

First, we're going to look at the collect method.2000

It's also known as map; you can call collect or map; they do the same thing.2004

It executes its associated block with the each element of the Enumerable object; again, you can define that each; and it returns values of the block into an Array.2011

For this example, we have this 1 to 5; we're calling the collect method, and it's adding them together.2024

It's going to do 1+1, and you see 2; 2+2, you have 4...all the way up to 5+5; that is the collect.2034

The next one is the select; it's also known as the find_all method.2048

Again, you are invoking the block for each element in the object; over here, it is going to return an Array of elements for which the block returns a value other than false or nil.2054

For our example here, we have this block: it's i.mod(4) if it's equal to 0.2067

This is our block: if this returns true, it's going to store it in an Array.2076

There are only two elements in 1 through 10 that allow it--that's 4 and 8; both of them are going to return 0 for the mod, so it's going to return that Array with 4 and 8.2081

The next one we will look at is the reject method.2096

This is the opposite of select.2098

In this case, it returns an Array of elements for which the block returns false or nil.2103

Here, you have 1..10; you call the reject, and this is the exact opposite of select, so it has all the other elements in this Array.2109

The last one we're going to look at is this inject method; it's also known as reduce.2128

It combines all of the elements with a binary operation.2139

Now, this binary operation can be a block, a symbol that names the method, or an operator.2144

We'll run through some examples.2155

It can be passed an initial value, too--so if a block exists, and each element is passed an accumulator value and element...2157

Here is an example: we have a range, 5 to 10, and we call this inject method.2169

It says, "OK, I have this sum value that I'm going to continue to create and build on, and the end result...I'm going to output that to you."2175

It says, "I have some value"--in this case, it's going to be 0--it starts out as 0--but it's going to add 5 to that, and then it's going to add 6,7,8, all the way to 10.2186

Then, you get your value, 45.2208

Notice, we didn't actually pass any argument here, but if you do pass an argument, 0, notice it's still the same 45.2212

It defaults to 0 by itself.2221

You can also have a starting state, so if I put a starting state of 2, it ends up with 45 instead of 45 there.2225

This inject method is quite handy, depending on what block of process you are doing in your object.2237

If you have a number of elements, you can use this each method, and it will process it to do some type of total.2247

Here is an example: if inject is passed a symbol, each element will be passed to the main method; so we have this 5..10 range; we have a symbol here that says I'm going to do some multiplication.2256

It's getting bigger, so let's do that...and then it's going to just multiply all of those numbers together.2272

Also, remember, reduce is the same as inject--so that is why we're using reduce now.2281

And then I do 2; if I do 2, which is my starter state, it's going to do 2 times 5, all the way to 10--whereas the first one, it defaults to just one.2288

You have to notice how there is a difference this is...times 2 will get you that value.2306

Other than that, that is the end of the Educator loops course.2320

Thanks for being here, and we will see you next time!2329