Procs Notes Day 2 Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

what is a proc?

A

A proc is an object that contains a block.
Example:
doubler = Proc.new { |num| num * 2 }
p doubler # #

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

how do you use a proc?

A

To do this, we need to use the Proc.call method:
doubler = Proc.new { |num| num * 2 }
p doubler.call(5) # => 10
p doubler.call(7) # => 14

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

how do you pass a proc to a method?

A
by assigning the proc to a variable you can pass it in to a  method as an argument:
def add_and_proc(num_1, num_2, prc)
  sum = num_1 + num_2
  p prc.call(sum)
end

doubler = Proc.new { |num| num * 2 }
add_and_proc(1, 4, doubler) # => 10

square = Proc.new { |num| num * num }
add_and_proc(3, 6, square) # => 81

negate = Proc.new { |num| -1 * num }
add_and_proc(3, 6, negate) # => -9

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

how do you convert a block in to a proc in order to pass it through a method?

A
you can cover a bloc to a proc by using (&) in the parameter attached to the block:
def add_and_proc(num_1, num_2, &prc)
  sum = num_1 + num_2
  p prc.call(sum)
end

add_and_proc(1, 4) { |num| num * 2 } # => 10

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

how do we convert a proc into a block?

A
by using (&) again but this time when you call the method you attach the ampersand to the proc:
def add_and_proc(num_1, num_2, &prc)
  sum = num_1 + num_2
  p prc.call(sum)
end

doubler = Proc.new { |num| num * 2 }
add_and_proc(1, 4, &doubler) # => 10

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