Procs Notes Day 2 Flashcards
what is a proc?
A proc is an object that contains a block.
Example:
doubler = Proc.new { |num| num * 2 }
p doubler # #
how do you use a proc?
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 do you pass a proc to a method?
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 do you convert a block in to a proc in order to pass it through a method?
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 do we convert a proc into a block?
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