Blocks, procs and lambdas Flashcards

1
Q

What is a ruby block?

A

A block is a bit of code that can be executed

You can use do …end or { } brackets

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

What is the collect method?

A

The collect method takes a block and applies the expression in the block to every element in an array

my_nums = [1, 2, 3]
my_nums.collect { |num| num ** 2 }
# ==> [1, 4, 9]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the yield keyword?

A

The yield keyword, when used inside the body of a method will allow you to call that method with a block of code and pass the torch or yield to that block.

Think of the yield keyword as stop executing the code in this method, go and instead execute the code in this block. Then return to the code in the method.

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

Are blocks objects?

A

No blocks are not objects and can therefore not be saved to a variable.

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

What are Procs?

A

Procs are saved blocks that you can name and turn into a method.

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

What are Procs used for?

A

Procs are used for keeping the code dry.

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

What is Dry

A

A programming concept : Don’t Repeat Yourself.

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

How do you create a Proc?

A

with Proc.new

cube = Proc.new { |x| x ** 3 }

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

What are the advantages of Procs?

A

1) They are objects

2) They can be reused.

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

How can you call on a Proc?

A

By using the .call method

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

How do you convert a symbol into a Proc?

A

with the & symbol.

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

How do you write a lambda?

A

lambda { | param | block }

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

What is the difference between lambdas and procs?

A

Lambda checks the number of arguments.
Lambdas count the arguments.
A lambda passes control back to the calling method.
Procs do not count the argument passed to them it just ignores needless arguments.

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

When are Curly braces required in ruby?

A

When you want to put the code in one single line.

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

Why would you like to use a Proc instead of a regular Method?

A
  • Gives more flexibility
  • you can store more in a variable
  • required in the database syntax
How well did you know this?
1
Not at all
2
3
4
5
Perfectly