Proc
objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.
def genTimes(factor)
return Proc.new {|n| n*factor }
end
times3 = genTimes(3)
times5 = genTimes(5)
times3.call(12) → 36
times5.call(5) → 25
times3.call(times5.call(4)) → 60
Proc
object, bound to the current context. It
may be called without a block only within a method with an
attached block, in which case that block is converted to the
Proc
object.
def procFrom
Proc.new
end
aProc = procFrom { "hello" }
aProc.call → "hello"
Proc.call
.
(
anInteger+1).abs
otherwise.
Proc.new {||}.arity → 0
Proc.new {|a|}.arity → -1
Proc.new {|a,b|}.arity → 2
Proc.new {|a,b,c|}.arity → 3
Proc.new {|*a|}.arity → -1
Proc.new {|a,*b|}.arity → -2
aProc = Proc.new {|a, *b| b.collect {|i| i*a }}
aProc.call(9, 1, 2, 3) → [9, 18, 27]
aProc[9, 1, 2, 3] → [9, 18, 27]
Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.