You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Kick off with the idea that this lecture will be tough, yield and things like self are hard
The key thing i want you to take away from this lecture is why do we need yield
It's very unlikely you'll be using yield much in actual ruby challenges but yield is important because it's fundamental to how the ruby language actually works
In saying that, a lot of the time as a developer you just use things, you don't have to understand how it really works, just get the job done
Array objects
classArrayend
The array class is like the classes we've already been building, but it's built into ruby for us, it has these invisible array instance methods
Recap on what is an instance method
To create an array object we don't have to do .new, we can just say arr = []
We don't get that weird object syntax when we create an array, we get an array, ruby does this for us
Look at array class docs, all of these methods are done behind the scenes
Adding methods to the array class 🌈
We can add to the array class
An example
classArraydefspecial_array_thingreturn'hello from special array thing'endendp[1,2,3].special_array_thing
Okay so we still don't really have the same behavior as .each
How can we make it work
We need yield
So what is yield
Yield and blocks
The formal explanation = yield invokes a block
Okay so whats a block 🙅♀️
A block is like a method in terms of encasing some code but it's special in that it gives some other programmer who's going to use your methods in their own projects the ability to customize the way the block works
An example of this is like a gem, a method call from the gem might allow you to use a block, and the way you choose to program that block is custom to your app
.each is a ruby method (array class instance method) which takes a block
.map is a ruby method (array class instance method) which takes a block
So i'm calling the .each method and then from the do to the end i'm inside of the block, the other syntax is using the curly brackets {}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters