Tuesday, October 04, 2016

Code Blocks in Ruby by Alex Chaffee

so now let's talk about block um
blocks are used all over the place and route
on there so ubiquitous that a lot of people don't even know they're using
when they re learn Ruby they're just following the example
and they don't know that every time they say the word do
they're creating a bloc and passing it in to a map it
but that's what happened a block
is a jungle coat the concept of blocks overlaps
not entirely identical with but it overlaps with the following
set up terms they're all waterways are doing the same thing which is
taking up one trip code: and instead of executing it immediately
making it in and a little capsule love code and then letting someone else call
it a little later
so some languages do this with something a function pointer
some languages do this with runnable
like Java you can't actually yet
have a closure in Java and you can't get a proper pointer to a function in Java
so you instead you make an object that has a method name
run and that's a runnable right
arm in javascript a function
is a function pointer really it's an object but it's also serve appointed to
its up to you to find a function you can then
just set the variable 2.2 that function and that
allows you to call it later if you want um
other terms prague lambda call back
front door delegates the sharp as something up delegates
and the other a lot like fun to play alright the basic idea is
it's a chunk of code that you're not going to execute
right now your executed a little later or maybe a lot later
or maybe never another term for what this is doing is it is real fining
Co to rate by does that mean the lakes and
rate means out on the tiles to rate by means to make it into a thing
it comes from the Latin term race between think
are yes right been to think up by
it's making coated with think Ruby
has 3 different well several different on Sat
that are very closely related on but
distinct a function which I should really call a method
but really doesn't have actual functions so when everything function in really
really mean that
a method is a chunk of code that starts with debt
that gets attached to a class and executed
by a map a dispatcher a block
is a chunk of code that begins with do that gets passed
into another map it and we're gonna see exactly how in just a minute up rock
is actually an object that contains
a block so
if you want to get a pointer to a block put it into a variable
you can't do that directly in rupee you have to make a block
and then make a proper out at the block and then point to the proxy the little
convoluted I'm gonna show you exactly how that works in the
starting in the next slide but just the I just wonder for these Terms out here
there's subtle but important distinction between methods
blocks and props approx is an object that points to a blog a block at the
chunk of code
and a method is also a chunk of code but was completely different calling from it
a block starts with do
curly braces a short and Purdue right
and it I don't like the curly braces it be better the curly braces didn't exist
it because curly braces are also used for hashes that a little ambiguity in
the language that's
irritating sup
every time you do as you this having to preview
every time you do started a blog so
69 as a method called times
and times executes that block this fax number of times
so if I'm I want to execute this code here
there by
I'm executing this I'm taking the sly hopeful
put a correct I am making it into a block
Rafael and then
Pines is calling that three times in a row
noticed that at the moment clear nothing is happening
it's the times method that is calling back
and activity mecca so
yes blocks can be wrapped in curly braces
a lot of people who are new to really prefer the curly braces
because it looks more like Java or C++ or JavaScript get over it
news do and rather than curly braces for the reason I just said which is that
with the curly braces there's an ambiguity
with parsing because it could be a hash
and that leads to some subtle annoying syntax error sometime
%uh indentation is also yeah it's
well depending on your editor it it technically there's no difference it's
just a simple
like do versus curly braces does the symbol for you should be able to figure
it out it's just
it's better to use do at
um we're gonna see in Justin a fewer flights
it's not actually a parameter or technically it's not a name
parameter it's an anonymous parameter and we're gonna see what that mean for
this to me
but yes it is being passed into time that's not in the normal way
so um blocks our youth for
lot the different purposes are used to solve lots a different problem
on the idea is that leave it up to the receiver the block to decide
what to do with that code and when or whether to call
so one thing that blocks are used for is called backs
let's say that you want to ask your network in library
to read in a TCP connection
and then as soon as that connection is closed take the content that
the entire can the entire packet
up love stuff that got past them by your network line
and past that into a block right so you're gonna call it later at a specific
but you don't want your code to wait for that to happen
doesn't I O found it might take seconds and seconds
you know but it's like eons to a computer you don't want to wait for that
to come so you make a block and pass a block in
and then you trust the library call that block later when that
data is available alright
you can also use blocks for initializer lease the initial life
let's say that um I'm writing a sinatra
said after the is the weather framework that lets you set variables
arm maybe at the time that you can clear your program you don't know what the
proper value it's
so you make a block that will be called later and %um
that block will know what the proper value with at the time but it's call
alright so for initializing bank but initializing them later on
not like when you declare the program but when you're running from
so some more stuff has been set up in the meantime
they're also use for iterator with we've been using a lot
their use for separating a content
the body of an algorithm from the boilerplate around but after
loops are the classic example the generators
keep track love initializing an index incrementally and that
grabbing the value and in the case map
collecting the results into a new collection
and then after having done all that standard stuff they call your blog your
block does
the specific stuff the idiosyncratic stuff that your particular
loop will need extracts comment boilerplate stuff
inside a map it and then called back in that case does like with time that
immediately but it's still a little bit later
and it still makes sense to do it it's not a call back in offensive waiting
for something happened long in the future
it happens immediately into the future but it still in the future
um it's also useful
for testing like that before block
in our spec write your specify a bit ago that's going to be run before every
examples back everything ok it block
by the way the if block is also a a do block it's also a
you know turns into a prop also it looks cool
sometimes your code it looks better you do things with blocks rather than doing
things in the exploded seaside
for lot stamina makeup on
yeah force or up
that's a another great example he didn't hear the
um sort for Team has a standard
comparison which is to use the flying saucer
but if you want you can pass in a customized sort blah
right the sort block would take two parameters the left side and right side
then return
you know negative 10 positive one but you can do whatever comparison you want
inside that block
sonya is a carried out sort do your configuring the algorithm
the way that you want
so let's talk about up rock keyword
crop terms a block into a variable or other into a reference
and then you can store that reference into a variable so in this case here
if I wanna say a
Prock do right in this case it's on one line so using
rates but I think prop do but I
that has made a reference to an object that when you call
that up to it will execute that block
and by call I mean say object outcall
so in this case I put it into a variable called say hi and then I say say I dot
and that will execute this book
and of course procs can take parameters
right blocks can take parameters and therefore proper call passes its
parameters in
block yes question
yet yeah and and I i've been
it a little technical but what's happening here is profits actually about
for act like a map it and then this is
the block so this if this is do but I and
that the find the block proctor that into a reference
and then meet a reference that call that executes block
so when you say call called us passes its arguments
directly into the blood
make that okay so
if I wanted to write aversion up times
that wasn't at school that a dumbed down version pot
I could do it this way I have a method called twice to do
that takes up rock which i'm naming action
could name it anything and is calling an action right now
and insider that meant that I'm calling it quite so now when I say
place do likely let me let me spell it out
I now have a variable say hi
and that variable adjusting the value that is actually a prop
so if I wanted to say say I dot call it does its thing
or I could pass that %um
as a name parameter and then placed he was gonna call it what
I'm now
I don't need to put into a variable if I don't want to
I could do that all in one go like that
place do crock do
but hi and
right so this same here to find the proper
and after that what's the proper gonna do well it's gonna do that
gonna do whatever i sat in the US
I now here comes the kicker
but the fault block so they've been called the anonymous blog for the
invisible blah
but it's called the ball
it is invisible and it gets past and just like this guy got past them
except instead of being passed into unnamed parameter
get passed into an unnamed invisible anonymous magic parameter
and on the inside a map it in order to call it
instead of saying action up call day
so if I wanted to do the thing I just did a crock but using
the default block instead this is the implementation about map
and now you see why I put that weird underscored do in the previous
methodName because now i can say place
do quote up alright but
that work yeah let me try that again
place to put hi at
so this year is equivalent to death here
but this second version is much more concise
and reads moral English E right it's got that
domain-specific language thing going on here
I can actually take place do this
it is actually a block I if I had said the word prop here that would turn it
into a named parameter
an explicit parameter but because I didn't it turned into it implicit
and this is something that magic and built into room
now I want to point something out this is not the only magic invisible
there's also one called self
all object-oriented languages most of the card
languages have a variable called this for sale
and that actually now the global that the parameter
it gets passed him to every function call
so that that function knows which objected that it's attached to
right now
the same thing happens here it's another invisibly passed in parameter to every
single map
most the time its black but
when you actually specify if the value is building
the only different yet between self and this guy is this guy doesn't have a name
it's not even called self it does help nothing it's called the default block
it's anonymous self at least has a name for himself
but this guy doesn't okay question
refile final
absolutely and we're going to see that in a minute
not right now but in a minute so I don't wanna
be labor this point forgive me for the late reply but as one pointed out
Ruby could have worked perfectly well without
invisible block it could have
worked just fine except that it would look like this
maps decided that this go down here
was prettier than this code up here it more concise and arguably it more clear
and that's the only reason why we have this weird
magic you know plumbing up
the default block which makes an anonymous parameter
past and every single map and that's weird
call yield which really means default block to call
right in just to make the language look nicer
and their other reason for that as well like there's
there are certain ways in which in with now crossed the magic wrestle
where we can make it means we can make our code look really super nice instead
of just a little nicer
but but this year place do but I
this allows us to make a method case twice
that looks for all intents and purposes like it's a key word in the language
so for instance yes right is a key word in the land
while is the key word in the language and
in is a while condition blah blah blah and
in this case they say place do blah blah blah at
it just looks like a departed language and let the language grow
right if this is Matt a program it makes it it does
make the syntax for method
approach the syntax for keywords
alright thats that the reason for it you might think that the done thing to do
but that's why they did okay
question yeah
no not at all I could name it twice but then I couldn't executed in the same
at up I could have named this that twice
fully by out I'll do that right now you up
night so now I can say place crock
do parts
hi and
I messed up but he didn't see this is why
the syntax get a little weird
I with Brazilian stuff if you don't follow the rules but
anyway there
that was just part in the net underscored it was a real
I when you let me put it this way when you call yield
if there wasn't the fault block it to run
rightfully right now take this call yielded of a block given
London in item
I have oh well thats I'm I'll of the original place but
yes like nothing no bucket
so if your gonna call yield you better make sure that the block
I'm sorry I'll
so course for the public to accept parameters just like any other block am
so here I say do with vertical bars
rather than parentheses
so here this is a block that takes a parameter
and then prince that parameter
with the string mississippi so here I am saying
yield with 0 and yield with one
and that way when I call that's this guy gets
0 print that
at 12 it because we want they want this is it became a 13 after a missed that
iraq for her unyielding 0 that this means I'm calling the default block with
the parameter
um and
let me show you a more advanced example a
blocks that take forever here I'm rearmament think each
and again this for underscore that's just my decision
for the name of that I didn't want to call it each as we've heard about a
method called he's on a red
but this one takes on a red so here we have a method
that takes unnamed parameter and a name with parameter
so when I call it I say for each
passing in the red and then I'm also passing in a blog
notice another little impact weird the do
have to be outside au the parentheses
you have for it
it's like a whole separate parameter left that can only have one item
I thought just going to this and a little more detail this
iterator initializes Ananda
says while that index is less than the size of the rat
grab a that item
pass it in as a parameter to this blog
and then incrementally iterator and then when we're done return self because
that's what you stop
not tell in the fifth Theoret right returning the original collection
is what he's
any questions on the flight
so blocks can also return bout just like a
regular old method they can accept parameters they can print stuff they can
do calculations and they can refer
so here's an example
map I'm reimplemented map on the outside
up an array rather than on the inside other so let's look at how this works I
think I initialize
the index and I make an array that
starts out empty and then for each item inside a bit I'm gonna heal
that item life retirement but the original array
ideal that item and then I take the return value and appended to the output
arrest and then at the end I return the output arrest so
in here doesn't works just like a regular map acceptance that have names
dot map
it map that name this block
accepts and item and reverses that occurred so this works
just like a raid on map accepted map over a questions on this
okay let me up
let me out how many people understand OJ
everybody's got a guy like that that's all I can expect for
well 25 in the morning Ananya morning and be
give you another okay let me move our
this answer the was a question that where
for which is what if you didn't get past the block in the spirit of duck typing
usually you should just fail if you're supposed to be passed in a blog and the
caller didn't pass in a block you should let it fail fail fast track bail early
fell off a
is the model a run the program right
you want the runtime errors to happen because that can all you've got
it helps the programmer right it helps the caller
if the receiver failed with bad day you don't wanna
protect the caller from sup so in this case
I'm assuming not the normal case but the case in which the method
works with out with a block past 10 but also works without a blockbuster
sup in that scenario I can call a method asking whether the block was passed in
the night that is Paul
block your and usually that's use in code like this:
instead of just yielded field here good luck with your
this is not the standard is that reveal you should have a reason for calling
block given and that reason should be that you know your method should work
with the block or without a blog it's a decision that
an actual proactive design decision the new blog given it's not the standard
okay here some relatively about
stuff sometimes you wanna write a map it
that tanks entered the fault block but then saves that block away
for later use in that case you have to turn a block
into approx money inside a map it remember
you can't actually store a block inside a variable
you can only store a block in approx and then put the prop in a very
so this is what does that if you say
ampersand and then name a variable
that's just the magic incantation that says
take the fall block make a profit for it and put it in a very common p
so later on I can store P an instance variable
or this API call remember it's a proxy is a prop to call
if it's just a block and you say you the little
disorienting I know I'm sorry I see a couple people
exploding sorry as well go on for much longer maybe we'll pick it up again
after lunch
but this is just the ampersand turns
the default block into a prop you can also
per approx into the default block
on the other side right if you're a caller
and you're calling a method to take the default block but you got up
prop maybe it's something stashed away from long ago
in your variable you can't turn back into the default block by using the same
percent that means the opposite
on the outside it means turn
up rock into the default block on the inside it means
for the potluck into a prop say sense but it's just completely the opposite
okay now up
I promise this is the last flight before lunch
I've been using or Prock all over the place sprocket blah
roomie has actually two types and closures:
really have props but they also have lambert's
proximal and other almost the same thing with to
very important but very subtle and technical differences
the first difference is that in a lambda
in cares about the number of parameters that you pass it
but in a profit doesn't care so
let's say that there's a proxy if you call the prop with 10 parameters
but the problem is defined do blah blah blah and with no brainer that fine
but it with the lambda then it would care
it would actually say wrong number parameters as like a method
the other difference there's even more subtle which is the behaviour return
if you use the term return inside of a block
if that block is in approx than that return statement returns from the
method that is calling it but if the tunnel and that it returns
just from the block
and that fact there just means never use return ever in your life
ever because it's too confusing cuz you're just gonna met you just gonna
mess it up
at some point in your life if you ever use return so just don't do it
does is if statements and then and at the very last line
seriously trust me has gotten me maybe okay in a year you can start using
returning to
but thats that's one of the reasons why I recommend
not using return at all because you might be inside a block
and that his return would return from the map it or you might be inside
Atlanta and that is with his return from
do and blah and the fact that
you might not know what's going on is just part I think you're looking at him
so you can use your kernel %ah
okay anyway
so now you might have enough information that in his lap
I have one more hint which is
the silly blocks lab are silly they don't make any sense at all
they're really done there's no reason why any real program or whatever right
that they have that way the problem is it's really hard
to write tests for teaching blocks
the letters give you a hint about the very first one
there's a method called reverser you need to write the method reverser
that method takes in a block that block returns a string
your method leaves the call that block and then reverse this trend
and then return that so it's weird because
there's just so many things going on so many moving parts right to test called
your method
with a block your map it call that block which oh by the way it back in the past
doesn't stop returned it back to your boat and then you do more stuff to it
and return it back to the test it's just insane
the hopefully have made it a little less than them by jumping around and waving
my hands
okay everybody any more questions for lunch
okay thank you

No comments:

Post a Comment