Last week I wrote a post about the differences between special blocks of code called Proc and lambda. This post will cover how these closures can get around scope gates and pass around variables defined that were defined outside of the current scope. To remind ourselves how scopes work in ruby, here’s an example
Now check out how we can pass the variable outer_scope with the yield keyword
As we can see, the method #some_method is passed a block kind of like an argument {|foobar|putsfoobar;putsouter_scope} which also passes in outer_scope from beyond the scope of the method.
Now let’s try using a proc
Here we’ve used a proc to combine the strings from inner_scope and outer_scope which was passed in when we defined new_proc and available to the method scope as some_var.
Proc and lambda are pretty similar (except for the differences discussed in my previous post), and we can change our method to use a lambda instead by
Thanks for reading, and stay tuned in for more posts!