Methods That Take Procs

When we pass a proc into a method, we can control how, if, or how many times we call the proc. For example, let’s say we want to do something before and after some code is run:

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."
end
say_hello = Proc.new ​do
puts ​'hello'
end
say_goodbye = Proc.new ​do
puts ​'goodbye'
end
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...
goodbye
OK everyone, I'm done. As you were.

Maybe that doesn’t appear particularly fabulous…but it is. It’s ...

Get Learn to Program, 2nd 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.