All language subtitles for pragstudio-ruby-15-blocks (Transcribed on 27-Apr-2023 20-39-09)

af Afrikaans
ak Akan
sq Albanian
am Amharic
ar Arabic
hy Armenian
az Azerbaijani
eu Basque
be Belarusian
bem Bemba
bn Bengali
bh Bihari
bs Bosnian
br Breton
bg Bulgarian
km Cambodian
ca Catalan
ceb Cebuano
chr Cherokee
ny Chichewa
zh-CN Chinese (Simplified) Download
zh-TW Chinese (Traditional)
co Corsican
hr Croatian
cs Czech
da Danish
nl Dutch
en English
eo Esperanto
et Estonian
ee Ewe
fo Faroese
tl Filipino
fi Finnish
fr French
fy Frisian
gaa Ga
gl Galician
ka Georgian
de German
el Greek
gn Guarani
gu Gujarati
ht Haitian Creole
ha Hausa
haw Hawaiian
iw Hebrew
hi Hindi
hmn Hmong
hu Hungarian
is Icelandic
ig Igbo
id Indonesian
ia Interlingua
ga Irish
it Italian
ja Japanese
jw Javanese
kn Kannada
kk Kazakh
rw Kinyarwanda
rn Kirundi
kg Kongo
ko Korean
kri Krio (Sierra Leone)
ku Kurdish
ckb Kurdish (Soranî)
ky Kyrgyz
lo Laothian
la Latin
lv Latvian
ln Lingala
lt Lithuanian
loz Lozi
lg Luganda
ach Luo
lb Luxembourgish
mk Macedonian
mg Malagasy
ms Malay
ml Malayalam
mt Maltese
mi Maori
mr Marathi
mfe Mauritian Creole
mo Moldavian
mn Mongolian
my Myanmar (Burmese)
sr-ME Montenegrin
ne Nepali
pcm Nigerian Pidgin
nso Northern Sotho
no Norwegian
nn Norwegian (Nynorsk)
oc Occitan
or Oriya
om Oromo
ps Pashto
fa Persian
pl Polish
pt-BR Portuguese (Brazil)
pt Portuguese (Portugal)
pa Punjabi
qu Quechua
ro Romanian
rm Romansh
nyn Runyakitara
ru Russian
sm Samoan
gd Scots Gaelic
sr Serbian
sh Serbo-Croatian
st Sesotho
tn Setswana
crs Seychellois Creole
sn Shona
sd Sindhi
si Sinhalese
sk Slovak
sl Slovenian
so Somali
es Spanish
es-419 Spanish (Latin American)
su Sundanese
sw Swahili
sv Swedish
tg Tajik
ta Tamil
tt Tatar
te Telugu
th Thai
ti Tigrinya
to Tonga
lua Tshiluba
tum Tumbuka
tr Turkish
tk Turkmen
tw Twi
ug Uighur
uk Ukrainian
ur Urdu
uz Uzbek
vi Vietnamese
cy Welsh
wo Wolof
xh Xhosa
yi Yiddish
yo Yoruba
zu Zulu

Original subtitles

Now, if there's one thing you're going to see everywhere in Ruby programs, it's blocks.

So it's time that we learn a little bit more about them.

Now, we're already using them in our program.

We're using blocks here in our test to organize code.

And in our playlist, we're using blocks to iterate through an array.

Now you'll find blocks everywhere in good Ruby programs.

Yeah, and many of the methods in the Ruby standard library also take blocks.

So to become an effective Ruby programmer, you really need to get comfortable with blocks.

So we're going to look at a number of ways to use them in this section.

In our movies, we'll use blocks to iterate through a number of movie viewings.

And then you'll use them to iterate through a number of game rounds.

We'll also partition out hits versus flops with blocks.

And then you'll partition out strong from wimpy players.

Finally, blocks will help us sort the movies by rank.

And then you'll use them to sort the players by score.

So let's start with some simple blocks.

Sure, we've seen that blocks are just chunks of code, and they come either between braces

or between do and end.

So let's try a couple.

So let's just start with a really simple single line block.

We'll just use put as and echo.

And so this is just a code block.

It comes between curly braces.

But by itself, we can't really do anything with it.

We can't run a block.

A block needs to be associated with a method call.

So let's associate it with the call to the times method.

So three dot times, we want it to run this block.

We run that.

We're at the Grand Canyon.

Echo, echo, echo.

OK, so that's just a single line block right there.

Now sometimes you want to do more than one thing.

And so blocks can also come between do and end, like that.

So let's say we want to do something like we want to print out sit up, and then we'll

print out push up, and then we'll print out chin up.

Right?

And in the same way, this block won't run by itself.

We need to associate it with a method.

So let's say we do this 10 times.

We want it to run this block of code.

So there we go.

We've got our exercise program all implemented here.

It printed out each of those strings as it looped through the block.

Now just like a method, blocks can also take parameters.

And block parameters come between these vertical bars.

Some people call them goal posts.

And we just give it the variable name, the block parameter variable.

We'll call this number.

And when a block parameter is here on the times method, times will assign to that number

each iteration number.

So if we then use the number inside of the block, let's say we use number right there

to print out the number of sit ups.

I'm just going to take that.

I'm going to paste it down here.

If we run this code, well, we see that it prints out the number.

Zero sit up, one sit up, and so on.

So that's just a block parameter.

It gets assigned as times is running.

And assigns each iteration into that variable.

As we've seen before, these block parameters are local to the block.

So if we come down here and we try to print out number, well, we're going to get an error

at the bottom.

Undefined local variable or method number.

Because block parameters are local to the block.

So we can't access them outside of the block.

Now sometimes these methods that we associate the block with take parameters.

For example, if we had the, let's see, let's take this and let's change it over to the

up to method.

The up to method takes a parameter and it's the maximum number to go to, let's say 10.

So here's the method name, here's the method parameter, and then the block comes after

the method name and the parameter.

So in this case, if we run it, we should start at 1 and go up to 10.

Because before we started at 0 and went up to 9.

And up to lets us bound that in a lower and an upper range.

So let's recap the various block forms we've seen.

Here we call the times method.

It takes a block which is simply a chunk of code.

In this case, because it's a single line block, we surround the block code with braces.

The block is associated with the call to the times method.

So in this case, times invokes the block, wait for it, three times.

Now if you have a multi-line block, the convention is to use do and end instead of braces.

And in this example, we used a block parameter, the number variable, to capture the iteration

number.

We refer to that variable within the block.

In the next example, we use the up to method which takes a parameter, the maximum number.

The block then comes after the method name and its parameters.

Finally, we've seen that the each method can take a block too.

Now methods like times, up to, and each act like a loop.

They invoke a block of code repeatedly.

And we sometimes refer to them as iterators.

Now in other programming languages, you might be used to more primitive looping constructs

like while and for loops.

But it's more idiomatic in Ruby to call iterator methods and pass them a block.

So let's put some blocks to work in our movie example.

You know, right now our play method, it just plays each movie once.

But what if we wanted to have a movie marathon?

Well, we could just change the play method to take a parameter which would be the number

of times we want to play all the movies.

So over in our play method here, we want to just change this so we iterate through the

movies and we play them all some iteration number of times.

So let's just start really simple.

Let's just try three dot times do.

And the body of the block is going to be this inner loop.

So we're actually going to end up with a loop inside of a loop.

We're going to iterate three times and every time through the loop, then we're going to

iterate through all the movies and have them reviewed and played.

So if we just go out to our flix file and we run this now.

Well, the movies are getting played three times, but it's really kind of hard to see

which viewing number we're looking at.

So let's change that around a little bit.

Back over in our playlist.

Instead of using three dot times, let's actually pass in a number here.

We'll just say this is the number of viewings and we're going to change it to viewings times.

And then we'll actually capture the current count as a block parameter there.

And then inside of here, we can print out, we'll just put a new line viewing and we'll

print out the count.

That way we'll know the viewing number.

And then because we changed the play method to take a parameter, we've got to go back

over to our flix file here.

And when I call play, I'll just pass in, I'll just pass in three this time.

So we get three iterations.

Go ahead and run that.

And we see that we've got Kermit's playlist.

This is just the setup at the top.

Viewing zero, viewing one and viewing two.

So all the movies are getting viewed three times.

Hmm.

But it starts counting at zero.

That may not be what we want.

Yeah, let's tidy that up just a little bit.

We'll close that down.

We'll go back over to our playlist.

Instead of using times, we could just use one up to, and we'll use viewings as the maximum

number there.

So then it'll start at one and go to whatever number.

So it should start at one and go to three.

I've got to run the flix file there.

There we go.

Viewing one, viewing two and viewing three.

That's better.

So now that the movie marathon is over and Waldorf and Stahler have seen the movies three

times, it would be nice to know what they thought.

It would be nice to separate the hits from the flops.

Yeah, now we could do this the long way.

We could just iterate through all the movies and then use a conditional to determine whether

it was a hit or a flop.

Right.

But Ruby has some other built-in iterator methods that makes this sort of list processing

a lot easier.

Right.

So to look at that, let's start with a simple list of numbers.

Sure.

So over an IRB, I'll just create a variable to hold our numbers, and we want this to be

an array.

I could use one, two, three, four.

Well that will create an array, but there's actually an easier way to create an array

of numbers.

We can set numbers equal to, we'll use a range.

We'll say one dot dot ten.

That's a range in Ruby.

We can call the two underscore a method, which will convert it to an array.

Now I've got a nice array of ten numbers.

Okay.

So let's say we wanted to select all the numbers that were greater than five.

Well, the way to do that is instead of using each to iterate through, we can use the method

select on an array.

Select takes a block.

So it's going to be a single line block, so I'm just going to put it between braces there.

Select gives us each element.

I'm going to say it's going to be a block parameter called in, and then I'm just going

to say I want all the numbers greater than five.

So what this does is it loops through all the numbers for us, hands us each number,

and then we have the condition in here.

We say we want a new array where all the elements are only those that are greater than five.

So if we run that, we get numbers greater than five.

Now this syntax may look a little cryptic, but don't let it throw you.

Let's look at this a different way.

We could also select all the numbers greater than five by using a do in block style, but

since it's a single line of code, we can write it all on one line.

Then we can replace the do and in with curly braces, and then we can further simplify it

by replacing number with a single character n.

And this gives us a really elegant line of code.

So there's no magic here.

It's just different syntax.

Yeah, and it's also fairly idiomatic in Ruby to write lines of code that look just like

this.

So let's have a look at a couple more examples.

Let's say we wanted to get all the even numbers out of our numbers array here.

So if we have our numbers array, we can call the select method that we've seen before.

We're going to get each element passed in in the block parameter in, and then numbers

have a method called even, so I can just call even question mark.

That's going to return true or false.

For all the elements where it's true, they're going to get put into a new array, and that

array is going to get assigned to the variable evens.

So we print that out.

Sure enough, we've got all of our evens in an array.

So how about all the odd numbers now?

Well, the difference here is we want to call the odd method on our numbers.

There's an odd question mark method, and we'll assign that to the variable odds.

So there we've got all of our odds that way.

Now another way to get the odds would be to do something like this.

The same thing that we did for the evens, but instead of selecting all the evens, we

could reject all the evens like that, and this would be the same as getting the odds.

Finally, if we wanted to just partition out the evens and the odds, there's a sort of

handy way to do this in one fell swoop.

We can just say numbers partition.

We're going to give that a block as well, and then we're going to partition.

We're going to say in dot even.

And notice here that we have two variables on the left-hand side, evens and odds.

For the array that matches the evens, it's going to assign that array over to the evens

variable, and for everything else, it's going to put it into an array and assign it to the

odds variable.

So if we run that, notice that we get a nested array.

We've got this array here and this array here, and it's nested inside of a larger array on

the outside.

So we've got a nested array, but Ruby's smart enough when that nested array gets returned

from this partition method, it destructures it into two separate variables.

So if we look at evens, it's just the array of evens, and odds is the array of odds.

Finally, let's say that we wanted to add up all of these numbers.

Well, there's another iterator method that's really handy to use, and it's the reduce method.

And what it does is it reduces an array down to a scalar value.

So let's say we wanted to reduce this array.

It takes a block.

In this particular case, it's going to give two block parameters.

The first one's going to be a variable that's used as an accumulator of values, and the

second one is actually the element.

And then inside of the block, we can take sum and add it to n.

So what's going to happen here is the first time through this loop, sum is going to get

assigned to the first number, which is going to be 1, and then we're going to say sum plus

n, so we're going to take 1 plus 2 and assign that back to sum.

So sum is going to be 1, then it's going to be 3, then it's going to be 6.

So that lets us accumulate values, and we end up with the total of all these numbers being 55.

So reduce takes this block syntax.

It also takes a slightly different syntax.

We can pass in a symbol with the name of a particular operator.

In this case, we want to add all those numbers together.

So we use a symbol and a plus, and it's just going to apply that operator to all the elements

in the array and reduce them down to some value, which would be 55.

So if we wanted to multiply all the numbers, we'd use the symbol and the times method.

You may see reduce, there's a synonym for it called inject, so that's often used in

Ruby as well, and we'll see reduce again later on in the course.

Okay now, so back to our movie.

Let's use partition to separate the hits from the flops like we did with numbers.

Sure, and we'll actually do that in a new method.

We'll write a method called printStats, and we'll just do the hits and the flops for now,

but later on we'll put some more statistics in there for the game.

Perfect.

So back over in our playlist class, I want a method called printStats.

I'm just going to give us some room here.

PrintStats, like that.

And then I'm just going to start it off by printing out that we have the names, stats,

just like that, so we know which movie name we're doing.

And then we want to partition the hits from the flops, so I'm going to have the hits,

I'm going to have the flops.

That's going to be our movies array.

We're going to partition it, just like we saw in IRB.

It's going to hand us each movie object.

And then to partition it, remember that we have that hit question mark method that returns

true or false as to whether the movie's a hit or not.

So we can just call movie.hit.

All the ones that match that criteria will end up in the hits array.

All the ones that don't will end up in the flops array.

So we'll just print that out.

We'll say the hits, and then we can print out hits.

And when we call putS on an array, it's going to call the toS method on each of those elements,

and we've got a toS method in movies, so that should work.

And then I'm going to print out the flops down beneath that.

Put us the flops, just like that.

Then we need to call this method, so I need to go back over into flix.rb.

After we've played everything, we take our playlist and we call the printStats method.

Let's give this a go.

We've got all of our viewings.

Look down at the bottom.

We've got the determineStats.

And in this case, we've got one hit and two flops.

Oh, Goldfinger really took a hit.

Wow, it's in the tank.

Negative one rank.

Let's just try that one more time.

Well, Goldfinger did even worse that time.

But we've got them partitioned out.

So as we run more iterations, we'll see sort of different behavior there.

Now the last thing we want to do with a block is sort the movies.

Right now when we print our movies, it prints them in the order we added them to the playlist.

Let's look at that.

You're right.

Right now we're adding movie1, movie2, movie3 in that order.

If we were to reverse the order, let's say we add Goldfinger second there and then we

run the thing.

Well, Goonies gets played first, then Goldfinger, and then Ghostbusters.

So it's playing them in the order that we added them to the array.

So let's step back and look at some basic sorting.

I've just got this sorting.rb file here so we can play around with it.

So let's say we have this array of names, Goonies, Ghostbusters, Goldfinger, and Godfather.

Now if we do the default sorting, we can just print out names.sort, sort as a method on

all arrays.

And if we were to run that, well we're going to get them in alphabetical order.

Goonies is last.

So that's basically the built-in sorting for characters or strings.

We can also do some custom sorting.

Let's say we wanted to change this.

We could use the sort by method and then we can pass it in some criteria.

And that takes a block.

It gives us each string.

I'll call this w because it represents sort of a word.

And so let's say we wanted to order them by their length, for example.

So we just call the length method.

Remember that's a string and strings have a length method on them.

So if we run this, then we get them in ascending order from the smallest word there to the

longest word, Ghostbusters.

Okay, now let's try some of that with our movie object.

So I'm just going to remove this.

I'm going to require our movie class there.

And let's just see what happens if we have, let's just create a couple movies real quick.

Goonies will be 10.

We'll have movie two will be, let's see.

Let's do Godfather with three.

With a rank of three?

Yeah.

Okay.

And let's do Goldfinger.

We'll split the difference and do seven.

Goldfinger, he went up in rankings.

Well, he needed to.

Indeed he did.

Okay.

And then we'll put them in array, movies.

We'll say movie one, movie two, and finally movie three, like that.

So let's just see what happens if we try to sort them.

Movies.sort.

Because it's an array, we should be able to sort it.

If we run that, we get this error, comparison of movie with movie failed.

So Ruby doesn't know how to compare two movie objects.

It knows about numbers.

It knows about strings.

But what about movie objects?

Well, we could do something like this.

We could use the sort by method and give it a block.

It'll pass us each movie.

And then we could do something like movie.rank.

If we do that, then they get ranked lowest to highest.

We kind of want our movies to be ranked high to low, right?

So we could, I mean, we could pull a trick here.

We could call the reverse method on that because that sort by method returns an array.

We can reverse an array.

And sure enough, that would work.

But that doesn't feel like the right thing to do.

What we really want to have happen is just to be able to call sort.

Because anytime we sort movies, we really want them ranked high to low based on their

ranking.

So we want intrinsically to movies to be able to sort themselves that way.

So how do we do that?

Well, to answer that question, when we call sort on objects, Ruby uses something called

the general comparison operator or sometimes called the spaceship operator to figure out

how things should be sorted.

Let me show you how that works.

If we have movie one up here, the spaceship operator looks like this because kind of looks

like a spaceship.

And then you give it another object on the other side.

So if we have like rank over here and we have movie.rank over there.

So we're just going to compare those two things.

I'm going to comment this out at the bottom just for a minute.

Got to do a put us there so we see what happens.

We get the value one.

We get the value one because the rank of movie one is greater than the rank of movie two.

So that's how it figures out, okay, this one's greater than another thing.

If we were to have, for example, movie two over here and movie one over here.

Well, then the general comparison operator returns negative one because movie two has

a smaller rank than movie one.

And if we were to compare movie one's rank with movie one's rank, it gets back zero.

So the long and the short of that is this spaceship operator or the general comparison

operator is used to figure out is the thing on the left hand side greater than equal to

or less than the thing on the right hand side.

And then based on that, the sort method can figure out how to sort things.

Now we don't want to be writing this everywhere in our code.

Instead, what we can do is we can leave movies.sort just as it is, go back over to our movie class

and actually define or override that method as a method in the movie class.

So we can create a method that is that general comparison operator.

We can pass in another movie.

I'm going to call this other movie.

And then inside of here, we can say what we want to compare.

We want to compare the other movie's rank to the current movie's rank, which is just

in the rank instance variable.

And if we do that, Ruby will automatically call this method when it needs to sort the

movies.

So we go back out to sorting.rb and we run it.

Sure enough, we've got our movies ranked high to low.

So let's put all this together.

If we go back over to our playlist where we're printing out the movies in this play method,

I can call put us at movies.sort.

That's our array.

So we could sort them when we're initially printing them out, as well down here in print

stats when we're printing out the hits, we could call sort there and sort on flops because

all of these are just movie arrays.

Go back over to our main program file.

We run it.

They're sorted at the top based on their rankings.

And if we look down at the bottom, we notice that Ghostbusters is hit.

It's the only one in that list.

And here we have Goonies has a rank of nine.

It's above Goldfinger, which has a rank of zero.

So we've got them sorted everywhere now.

So in this section, we used a variety of blocks to do a variety of things.

And in the exercise, you're going to do some similar things.

You're going to iterate through a number of rounds.

You're going to partition strong and wimpy players, and you're going to sort your players.

Now we promised you earlier that we would revisit symbols.

So we're going to do that next as well as learn about a new thing in Ruby, Strux.

Sounds good.

Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.