Tuesday, October 04, 2016

An Introduction to Procs, Lambdas and Closures in Ruby by Peter Cooper

welcome to an introduction Jeep rocks
lambdas and closures in Ruby for your blood type for that gives a little bit
am this is really a short side section may be reloaded course but you may be
viewing miss
in some other way on YouTube whatever so hello everyone and feel free to check
out the course that route really reloaded dot com
if you are a not part of course I'm frequently running
will be training courses on there so what you might find interesting so
someone needs to video about walls in Ruby what
are approx what all and is blah closures
and how they all kinda work with each other how they were like
now I'm really gonna stick to the basics in this video
just enough you'd stop playing along and see you you have hit up the pitch it
Orioles are available out there is
so much stuff out there am I'm gonna look enough you know tricks along the
so radical start with a try definition let's get there
with some examples so you should be familiar with the concept of a block
in Ruby looks are essentially nameless functions are the souls let's just get
one oh well
so we get a feel for you know what's going on
so when I'm done here is I've created a right contains the numbers 1 to freedom
I then have the each methadone
array and then I passed a code block so that's section hey between the do
and be and and if I save this and run this
you won't be surprised to see result ease one to
free full we could also right not in a slightly different way
as you're probably aware using am
curly braces I'll just do it manually here so you can
say that the process there this is kinda the recommended web doing if you gonna
do things
as a one-liner and you can see that runs in exactly the same way
solo said behind-the-scenes
each is essentially an iterative methods available on the Array class
that accepts a cockblock was passed to it so we've got a codebook is print
something out
and but each element of the array that code book is ROM
so that's why we get to see once a freefall come out but Kobach is Ron
for each thing for 1-for-2 for free for four so being dynamically run multiple
times by another method
each behind-the-scenes nosedive already shows off the
the idea blocks as nameless portions of code a continuous functions if you wish
at the county parks pretty much anyway
and then which me run arbitrarily most often in the loop
abstractions in our like this one so we we've gone over and something a certain
amount of times
now the interesting leap that we can make here
is that we can make our own methods except blocks in a very similar its age
and %uh stuff with those blocks so war start with the most simple most useless
alleged example
by a creating a method in the main context I have a an example ready here
so wanna go here's a guy mythical run-blocking all it does
he's column ethical yield will get swine and second
and then we have a cold to run block am reposting cockblock so again this could
be curly braces all on one line but which do it with a dude named
so what's happening school
if we just run the code it prints out hello world
that's fine what's happening will when way
running run block here we essentially calling the run block Bedford
passing is cockblock and then yield
is another method essentially you lose control to a poss blocks within the
I'm currently a context what happens if we don't pass a block so what happens if
ice get rid the block and on me run that we get our
an exception and local Jumeirah notebook given
am on the yield wise is occurring
will yield is looking for your code books been passed
so the the current method it can't find one it files
luckily however there is another method that we can use to check with our block
was given to a method or not and %uh that is called block
on the school given query and if I put this it will only run yield
if you block was possibly right now pretty much nothing occurs
so Liz extend their example it now
and again I have another example here let's I random
underscore each method to the array trials so do they ever
monkey patch a and it work a little bit like a try we did in the first example
but it will go through an array in a random order
so if we don't do this what on his I've opened the
Array class and then I've created the random each method I've used arrays
built in shuffle method to
shuffle at the rain to random order and then using his normal
each method and passing it disco blockade
which then in turn yields
to whatever kodak has been passed into random each
with each element of the shuffled around
source having here is like rated know right takes one two three four five
and I call random each to random each online
possible miss cockblock the prince on element so
this code block area ends up
being attached around the beach essentially once we get into this
section here
it does the shuffle it loops over and then
it will yield to this block area
each element comes out the shuttle to write so if we run that
we get five free 421 it's all in a random order
now there's another way that we can write this the law allows to get better
but I to grip a bit more of control
on the cockblock so let's see I have another example him
now this is slightly different in this case we use a special for my hair
I'm in the list of promises so normally it have a list your promises here
and but then at the end what you can include you can include ampersand
and an argument so what this will do is any cockblock is being passed along
it was assigned to this parable so be we'll send you become a reference to
that cockblock
as being passed him so within the random each method now at this point we run
this code
which as you'll see runs pretty much like the last example
be now represents that code blocks we know implicitly calling it would yield
or something like that I'll check in with block given
we are now using be explicitly am so that's what's happening here wouldn't be
don't call and then the element we wanna passed since the
promise to hit so what's going on here what he's barely managed to get
an object ok see at this point what is based so we can check this by
using the team effort to can happen little bit an expectation of
be and if we run this
we gets but comes up here I Prock
so it's approx object and we've now pretty much got a definitional
Hove what April object is its sensually a nameless
all as is often called anonymous function or block of code
that can be represented as an object and can be passed around
and called it will
up the he's a key difference between proxim blocks we need to check out
and that is that you can only passed single block to a method to the time
so disease pretty much a baked in restriction in Ruby
but what you can do is you can pass most approx around
am his promises to am Gary methods because
props a regular objects like me past Renekton array or string
whatever you want and that was no demonstration here
so what we're doing is ignores method for now we create a prop
and see this in text here actually using propped up new now
to actually crap rock and of props doing is just saying
you know pretty much hello to the world here at this problem this is procter
those we have two procs
and we are calling the wrong to procs method
and we're passing in the props just as if they were any other type object
so if you see him now have this method is set same I am bases bringing prop one
son in July Mb and then with which we just do it I don't call
and if they don't call and everything's pretty much got the got
so pretty pretty handy
now I need to show off guam interesting trick at this point because you may
encounter in
every Cody looking at those out there essentially if you have a method is
being passed the cockblock
as we saw earlier you can call it would yield we sold out
all that you can use the ampersand augments converts into a prague
which you can run within the method was seen as well
there is however a third-line
and let's look at the hem Sosa for some little on the the prior examples we had
we have a
method could run block and weak coal run block
week posit a block but instead old
you accepting something in here all using yield
becoming a little bit the next for the two we have a
actually have to put he's pretty a specific promises up here
ramps and promise for whatever all we've done is we've called prop don't you
and the reason this works is if you use proper got new
with annals giving a cockblock to assign to that Prock
prop Tony will look to see if the current scope has been passed a
and it will use that so in the interests or implicitly you know I am at a special
anything here
the fact is I did not put another Kobach in here
so it's gonna you know pretty much look for that for me
and then applying now if you trust do
in Scopus not been passed a cockblock it will raise an error so we come
so very a you quickly proved that get rid of this
and run this and it says you know we tried to create
approx object without a block so essentially problem he wants a cockblock
to use with cricket directly
Oricon implicit picks one up from you know the cars got the current
now in maybe 1.9 therefore mine waste coal
all run a block so let's look at each of them quickly
now here which is defining a prop has one from its a
I E and its prints at this is my pro and and then put in whatever was passed to
and we called it my aunt school Prock so he's the first way that we can call it
we can use call effort we've
use this in prime examples and we're just passing in 10
was the argument another white this is a typo it might look a little bit light
we used dole's prophecies and in arguments
and what happens behind the scenes is am cut interest in one actually
is that that actually gets converted 2i Cole
is basically a synonym for calling don't call
leave work on nonprofit objects if the imprint call method
so is it we it is you know a little bit further we had syntax trick we going on
there but that's another way you can get in
another way is to use am square brackets
and last but not least you can use triple equals
and not much a little bit which you will just run this to see you can see that
knows is definitely working
we get this is my problem 10 and 20 30 forty
so what's this trip legal single about bull
in ruby that triple equals operator is called the case
equality operator and its primary function
he's each get used within K statements let me does have some other uses as well
but K statement sees pretty much the reason this came about this
syntax specifically for proxy anyway so
without going into too much detail he is a little less exploration very
contrived emotionally now with Craig quite a few proxy we've created
am proxy and I've been assigned a variable school several many few couple
unknown witchu
give a little bit have a clue about what they the check in full
but each have a single promise which is number
and that comes in and all we do is we just do best
a logical check in all these cases will check to see
is numbered I'm a free and less tonight
and if it is the several prop you know will return true/false accordingly
and which it's yours by Fri and underwrite for the many
few check to see the number is exactly free the couple
to a non 0 and what we do here is really ran the numbers from
0 up to 10 and the game using the Cobra okay but said
we don't worry too much about this code of us could up to is a handy map
and we get number coming in we say that number items is
and then we saw the pack a statement now hope you're familiar with K statements
if not this may seem quite confusing to you
but what sets you were doing is we're saying you have
query a number at this point and then what normally happens in a case
he's if we had something like am
let's say we had the same unit number five ish number is equal to 5
%um now print several as we do this kinda construction and what happened
behind the scenes
is we would have 5
it was it was equal number so that was a little bit back to from this is what
happens in Ruby so it takes
each thing goes through the list and then it takes the actual object here
does the case equality operator and then whatever is
the is the subject of the case statement
so what is happening win we have this type arrangement when several women you
in few and so on and so forth
well we come in first but it will do is it will take several
okay let comment here it will use the
case equality operator upon it and then
it will have number but rather actually doing economy quality check
as it would do if we you know had a number or something almost talk two
what happens is it takes the several Prock
and it calls it passing in number so number makes it to hear
it checks the sea is this true or false if it's true
will run this piece of code its falls it but we'll move on to the next thing
such really what's going on here now if you have used K statements about you
might say we could just use the range here or something almost hotlines you
could've said
you know 4.7 or something along those lines because
4.7 Eagles Eagles Eagles as a5
with them you come out the truth
but we must abstract everything away into prague objects
which them being cold behind-the-scenes essentially
used in that case equality operator by Ruby says cut a clever trick
allows you to abstract away interesting bits functionality
and I must admit I've only use this a few times really in any kind of the
actual lives in RI it's not something that's a
I'm always pulling out the for the back but really worth knowing about this
am in its a nice little trick
sucker let's move on to lambdas love it.
will their sentry Procop checks that you know the hell
pretty much they all pro club Jets somewhere about that um
but I have a couple different behavior so this distinguishes them from
just plain ol procs now most of the simple deming
silo what we got going on here well it looks a little bit like an assist to
make you know we have propped up new
not type thing have some code in then call it
unit nothing too surprising well what I can do is unchanged at prop not new to
and just as a quick aside: actually I don't have to change that I could change
to prop
and that is actually a shortcut way alt every is doing the same thing the proper
new does
such a shortcut way I'm just writing essentially the same thing
and the reason why you might want to use it is because
in Ruby 1.8 writing prop will actually create a lambda
so it gets a little bit confusing ambiente 1.9
is treated in a pretty much the way you would expect
the back to lambdas
so thats run this code you see it was exactly the same way as it did with the
prop so what's the difference will
one key difference ease thats lambdas in force
arity what does that mean essentially means that land is of particular battle
having the number the premises and the number volumes involved match up so
a lender expects to be cold with many as expected receive
risk ratio you demo cuz again but as always the best way shiny things of it
sort of God is a girl &a we have them your free france in here AB and C
but when we call it when i text passing anything says nothing Arabian Sea to the
so if we just run this
they say is wrong number of arguments 0 for free so the lot like a a method
in that respect you know it's not gonna so Stanford nonsense in that regard
ways to change this and reminisces 1.9 the way we doing this
but changed the prop in this case
it works fine and what's happening in this case
is that AB and C will be set to nil because there's nothing for them to grab
so they'll just the fall to nail wears a lambda
act a little bit more like a method with for its premises
and it will just give up for the exception
so another key difference he's in am
landers and prop Bryn return semantics
so a gain you know another really quick demo
when I got here is I create a single method called run-up rock
accepts the product comes in as pay and what we do is
we say literally Prince the street at this point
we're gonna start running up rock call the prague and then we say we finish
running the prague
so if we break this up a little bit the first thing that we do is we call Ron
approx and we possible and a
the principal itself it will say I'm a lambda
and then this returns a bit like you do in a method we have a return
we didn't know a.m. to hip
and then what we have followed up with that is we have exactly the same thing
but with approx so the Landis is a plane Prock
object now if we run this
with the lambda we make in to run the project says something from the prop
designer lambda
and this is finished running the prague be women we used the normal prop however
the bare-bones prop it was a starting to run up rock on the prop
and then woohoo exception unexpected return
what's going on him will the reason for this is that a return in a Prague
will try to do return from the context with the problems defined
so not where is currently running wheres actually define
am so since that's in the main contact so weak she defined the prop hiya
this returns trying to return from ask ok out here
which the main context and you can't return for the main concepts so we have
a big issue on our hands but we can tweak this to actually you know
reach the end the program so what we do is move on so this
what I've done is this is really really simple web doing I Chris another
our program which I call later on
so this is just really wrapping this up very simply
we going to exact same thing from the lambda run the prop
and from this you get see lambda
in runs out fine the prop even
set on approx we never see finished running the prop
and the reason for that is that when we get to this point wheat pasta approp
makes into here we print l: starting from the prague
P to call because it's doing the return
procs return from where they had to find that concept with a defined which is
so this very point when we done this call it returning from HEA
back out and exits out program
so that's why we never get to this line him
now I just have to do want to change it will really show this off for you so
we're just quickly do a little %uh
tested this so we'll switch around the problem the lambda
this will really show you the kinda how far this technique guys were run this
and only does this time it starts to run the prague on the prague
we see no more we don't even see the lambda all
anything like that old so
literally at this point is run this is pushed in this product
up to here calls it the return drags right now about program
and then back down to the bottom paint where the program terminates
now at this stage before we move onto
I'm closures which is that the next arena deal with I just wanna recommend
to you that
you check outs I am a page in the Rebbe documentation so we need to do
search for Ruby Prock and Google that
the first was always use the app the redox site
and it was a docking station for the prop class
and it has some pretty interesting methods on their now remember the procs
include land is even though they urged slight for flavor approx
and their few interesting methods and including lambda
query which allows you to Oscar pro are you a member or not
that may be useful t8 animals a source locations one of my favorites
which tells you which file and where you want line and everything a property find
and this committee had to make your little testing library and things like
am if you are on the really low because we've seen how I put together the test
testing library I developed and I pretty much used acts and
source location effort to could affect
so closures what a lovely
all in Ruby closures very much like what you've seen already
so you take something like a an enormous scope local functions on this year in
approx object
but one that maintains references to local variables
that will present and being used at the time with the and
me a definition of that code so as with everything else
demonstration it probably just what we need here
so she's quite simple what we've done is we've got a local variable could name
and really you make a point to a lovely string object
at the contains the name Fred and then we have another
there will be a printer name which is associated with this project
all it does is it just prints out name to the screen
and then we have to be seen it a few times a rump rock method
that just accepts approx has you know announcement comes in
and runs that runs out with the coal of we got will
you know making get this worked fine which run this printf renounce the
screen but
if you think about it really logically name exists here
it doesn't exist in this copia
so when we doing this puts name something magical must be happening
so that when this prop makes into p and then it's being called
that much make name come to come back to life weaken
access it once again that kind of magic
he's called closure so
what's actually going on here ball as you can see
months we define name we do that puts name
name is treated put into the closure its console that you know we actually using
name within that prop
and that's what we're gonna get bloated that's why it would be no hang around as
part of the problem
means it can be used later so let's just look at a slow process like interesting
example which
shows how we can use a closure to dynamically defined function behavior
so I quite like this one Reza Khan example you'll see in
love the books so what I've done here's I cross the method
school multiple generator and this is
a method actually create at lambda object for us
and what we do is we just do is pass in a number such a multiplier
it to create a lambda which intern
except the number it most was that number why the motor multiple that's
come in for em
and that's it very simple sort done is
I've created at double-a and triple-a so all you do is you call most will
generate with two and free
and what that would do in turn is it will create a lamb to the x6 a number
and then take that number multiplies it by to in this case
all my free in this case so what's actually happening is when we're calling
multiple generate 22
n comes in and then exist so %um is equal to two at this point
and then a.m. east or even the closure of this lambda
so then that lamb to condemn you later on as it is here
which puts double-a 5 I could be da cold we just used square
am brackets for next a little bit the change here
and 102 is ill print out 10 and if we take the triple-a
because free is now im
we get thirty so here I am NOT pretty much as expected
now British closed have an interesting behavior compared to some other
which some other languages they closures will be implemented with it they
structured schools
the variables and their values at the time the closures created
but in Ruby million reference is kept so those their bills
so it means that the contents those variables can be changed before the prop
gets a chance to run
so let's jump back to a copy a prime example
and see that in action
so this is a lot like the example we did just a minute ago where
we you're taken 9 a.m. we print out that name
am in approx but then what I've changed what name seek to this point from Fred
to John
so you may think well OK at this point the closure was formed when we need to
find the product
so you know it might set maybe it will be freight revenue also what to do P to
call will proofread
but because I would have just explained about keep reference
to the variable rather than the value of the app is very time
what happens is we run this and we get John
so in this case name became part the capture but because the value then
changed repeat a reference
the updated values recognized as names value in the closure
at the time is called as well now is a lot more
closed it but that is very basic introduction as to
what they're all about and if you are part of the review will only cause our
actual even if you watch this on you should not leave a comment or something
feel free to say he wants policy per slightly more advanced you're digging
into a specific thing
I really want is provided the basic vocabulary here in the basic example
so that now when you encounter these of things you understand roughly what's
going on
am rather than producing some but we had edge cases it was never bump into
in production code so this week while on my butt
if you are public also whatever coming to the forum
request the video and more than happy to produce it fully
so that's it for now a very basic introduction to
blocks procs and closures
hope you enjoyed it

No comments:

Post a Comment