Blocks Flashcards
What is a ‘closure’?
A closure is a general programming concept that allows programmers to save a “chunk of code” and execute it at a later time.
What are the three main ways to work with closures in Ruby?
1) Instantiating an object from the Proc class
2) Using lambdas
3) Using blocks
What is a block in relation to a method call?
The block is an argument to the method call.
In other words, our familiar method, [1, 2, 3].each { |num| puts num }, is actually passing in the block of code to the Array#each method.
Why is it that sometimes the code in the block affects the return value, and sometimes not?
The answer lies in how each of those methods are implemented. Remember that the code we wrote in the block is not the method implementation – in fact, that code has nothing to do with the method implementation. The entire block is passed in to the method like any other parameter, and it’s up to the method implementation to decide what to do with the block, or chunk of code, that you passed in. The method could take that block and execute it, or just as likely, it could completely ignore it – it’s up to the method implementation to decide what to do with the block of code given to it.
Know how to distinguish method implementation from method invocation when a block is passed. (sometimes the invocation block will be longer then the implementation code)
# method implementation: def say(words) yield if block_given? puts "> " + words end
method invocation:
say(“hi there”) do
system ‘clear’
end
Why is it useful to use blocks to defer some implementation decisions to method invocation time?
It allows method callers to refine a method at invocation time for a specific use case. It allows method implementors to build generic methods that can be used in a variety of ways.
break this method down into its parts:
[1, 2, 3].reduce do |acc, num|
acc + num
end
[1, 2, 3] is the caller.
reduce is the method call
do….end is the block
How does (&:method) work?
First, Ruby sees if the object after ‘&’ is a Proc. If it’s not, it’ll try to call to_proc on the object, which should return a Proc object. If not, this won’t work.
Then, the ‘&’ will turn the Proc into a block.
What is the variable scoping in relation to closures?
Closures drag their surrounding context/environment around, and this is at the core of how variable scope works.