Functions and Blocks

Proc in Ruby

A proc is a saved block of code.


Syntax
procName = Proc.new { #block of code }

#convert block into proc
&procName

#calling a proc
procName.call

Notes

Procs are objects but blocks are not. Procs, like methods, can have a return statement. If a proc is called (not yielded to), it exits the calling method (unlike lambdas).

Procs are often passed into methods (after conversion to a block). In this case, when the method yields, it yields to the proc.


Example
def goToBed
    puts "An alarm needs to be set before bed."
    time = gets.chomp
    yield(time)
    puts "Good night!"
end

#proc declaration to set alarm
setAlarm = Proc.new { |time| "An alarm was set for |time|" }

#setting the alarm before bed
goToBed(&setAlarm)

#randomly setting the alarm
setAlarm.call 

See Also
Related

Blocks
Yield

Documentation

Class: Proc - RubyDocs

Add to Slack

< Yield   |   Lambda >

© 2018 SyntaxDB. All Rights Reserved.