I'm not sure I see the application for this. Calling a subroutine makes sense, but it seems you have to do the same work each time in the block every time you call the yield. Isn't one of the main points of functions (or things that act like functions) to reduce duplication of code? Or maybe I'm missing something about how/why yields work.



The examples given are only here for the sake of learning, it's normal if you don't see a real application yet. Just keep in mind that the guys (or gals) who made this course are experienced and know what is useful and not useful to learn. If it's in the course, you should assume it's useful. Of course if you want to know exactly why it's useful, it's great to do some research on the subject by yourself ^^.

The point of yielding is to be able to pass the execution to a block of code you don't necessarily know about, without having to worry about what it will be.

For example:

symbol_filter = lambda {|x| x.is_a? Symbol}

symbols = my_array.select(&symbol_filter)

The method select has a yield somewhere in its code (or anything similar, like the call method) to be able to pass the execution to our lambda at some point. Obviously the coder who made this method didn't know and didn't care about what kind of filtering we wanted to do with his method, but he assumes we know how to use it (because we read the documentation ^^) and that we will pass it what it expects.


Thanks for explaining! i was wondering the same thing.