Blocks Flashcards

1
Q

What is a ‘closure’?

A

A closure is a general programming concept that allows programmers to save a “chunk of code” and execute it at a later time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the three main ways to work with closures in Ruby?

A

1) Instantiating an object from the Proc class
2) Using lambdas
3) Using blocks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a block in relation to a method call?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why is it that sometimes the code in the block affects the return value, and sometimes not?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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)

A
# method implementation:
def say(words)
  yield if block_given?
  puts "> " + words
end

method invocation:
say(“hi there”) do
system ‘clear’
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why is it useful to use blocks to defer some implementation decisions to method invocation time?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

break this method down into its parts:
[1, 2, 3].reduce do |acc, num|
acc + num
end

A

[1, 2, 3] is the caller.
reduce is the method call
do….end is the block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does (&:method) work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the variable scoping in relation to closures?

A

Closures drag their surrounding context/environment around, and this is at the core of how variable scope works.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly