Ruby Proc Objects
A block can be stored as an object called a proc. A proc keeps the block code and runs it later with call.
A proc stored and called
shout holds a proc that upcases a word. call runs it with the word ruby.
shout = Proc.new do |word|
word.upcase
end
puts shout.call("ruby")Capturing a block with &block
run_twice captures the caller block as task. call runs that block two times.
def run_twice(&task)
task.call
task.call
end
run_twice do
puts "Step done"
endProcs kept in an array
Two procs sit in one array. The first one runs with call and prints its line.
jobs = []
jobs.push(Proc.new { puts "First job" })
jobs.push(Proc.new { puts "Second job" })
jobs[0].callExample
def wrap(&action)
puts "Start"
action.call
puts "End"
end
wrap do
puts "Middle"
endKey points
- Proc.new builds a proc from a block.
- The call method runs the stored block.
- A proc can receive values through call, just like a block receives them from yield.
- An ampersand before a name in a method definition captures the caller block into that name.
- A proc stored in an array stays ready to run later.
In this example, wrap captures the caller block as action. The method prints Start, runs the captured block with call, and then prints End. The three lines show the stored block running in the middle of the method.
Note
A captured block arrives as a proc, ready for call.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a stored proc run its block?