Methods That Take Procs

When you pass a proc into a method, you can control when the proc is called, how many times it’s called, or even if it’s called at all. For example, let’s say you want to do something before and after some code runs:

1: def​ ​do_self_importantly​(some_proc)
puts ​"Everybody just HOLD ON! I'm doing something..."
some_proc.​call
puts ​"OK everyone, I'm done. As you were."
5: end
say_hello = Proc.​new​ ​do
puts ​"hello"
end
10: 
say_goodbye = Proc.​new​ ​do
puts ​"goodbye"
end
15: do_self_importantly(say_hello)
do_self_importantly(say_goodbye)
<= Everybody just HOLD ON! I'm doing something...
 hello
 OK everyone, I'm done. As you were.
 Everybody just HOLD ON! I'm doing something... ...

Get Learn to Program, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.