Name

Proc — Procedure object class

Synopsis

Proc is an objectified block that is given to a method. You can create a Proc object by calling the proc method or by using the block argument of the method.

p1 = proc{|a| a + 1}    # Proc from a block
p2 = proc               # Proc from a block given to this method

def foo(&proc)          # Proc from a block given to this method
  proc.call(42)         # invoke Proc, equivalent to yield
end
Proc::new
Proc::new {|x|...}

Converts the block into a Proc object. If a block isn’t passed, the block associated with the calling method is converted into a Proc object. Equivalent to built-in functions lambda and proc.

Instance Methods

p[arg...]
p.call([arg...])

Calls a Proc object.

p.arity

Returns the number of arguments accepted by a Proc object p. For p that take a variable number of arguments, returns -n-1, where n is the number of mandatory arguments. Notice {|a|} gives -1, since it works like {|*a|} when multiple arguments are passed.

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

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.