Example uses of 'Proc'
A Proc (short for procedure) is basically a method that is stored in a variable; it may have formal parameters enclosed by pipes ("|"). The Proc is called by sending the message call to the variable; any parameters given to the call method are passed along to the Proc.
Procs are closures:The context in which the Proc is written is "sealed up" and included as part of the Proc.
| A trivial Proc | |
p = Proc.new { puts "hello" } |
p.call |
hello |
|
| A Proc with parameters | |
p = Proc.new { |x, y, z| puts 100 * x + 10 * y + z } |
p.call 14, 9, 2 |
1492 |
|
| Same Proc with parameters, using 'do' | |
|
p.call 122, 12, 25 |
12345 |
|
| A Proc that demonstrates how "closure" works | |
|
|
19 |
|
| A Proc with a meaningful return value | |
|
puts max.call(0.8, 0.12) |
0.8 |
|
| A block passed as a parameter to a function becomes a Proc | |
|
foo { puts "Hi!" } |
Hi! |
|
| Procs can be used to create variations of a method | |
|
|
|
|
| The 'lambda' method explicitly creates a Proc from a block | |
|
|
Hello to you, too! |
|
| A block parameter must be the last formal parameter | |
|
|
1049 |
|
| A block can be optional | |
|
|
|
|
| Another example of using a Proc as a test | |
|
|
|
|
| Here's a function with varargs and a block | |
|
|
|
|
| Another example of closure carrying context | |
|
context |
|
|
| Loop from Range#min to Range#max by steps of n | |
|
(7..20).my_step(3) { |n| puts n } |
|
|