Programming Ruby

The Pragmatic Programmer's Guide

Previous < Contents ^
Next >
class Proc
Parent: Object
Version: 1.6


new [ ] arity call

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 {|n| n*factor }
times3 = genTimes(3)
times5 = genTimes(5) 36 25 60

class methods
new [{| | block } ] -> aProc

Creates a new 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
aProc = procFrom { "hello" } "hello"

instance methods
[ ] prc[ [ params ]* ] -> anObject

Synonym for

arity prc.arity -> anInteger

Returns the number of arguments required by the block. If the block takes no arguments, returns -1. If it takes one argument, returns -2. Otherwise, returns a positive argument count unless the last argument is prefixed with *, in which case the argument count is negated. The number of required arguments is anInteger for positive values, and ( anInteger +1).abs otherwise. {||}.arity 0 {|a|}.arity -1 {|a,b|}.arity 2 {|a,b,c|}.arity 3 {|*a|}.arity -1 {|a,*b|}.arity -2

call [ params ]* ) -> anObject

Invokes the block, setting the block's parameters to the values in params using the same rules as used by parallel assignment. Returns the value of the last expression evaluated in the block.

aProc = {|a, *b| b.collect {|i| i*a }}, 1, 2, 3) [9, 18, 27]
aProc[9, 1, 2, 3] [9, 18, 27]

Previous < Contents ^
Next >

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

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.