Proc

From RubySpec

Jump to: navigation, search

Proc objects - short for "procedure".

Procs are first-class objects, since they can be created during runtime, stored in data structures, passed as arguments to other functions and returned as the value of other functions.

...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 gen_times(factor)
    return Proc.new {|n| n*factor }
  end
  times3 = gen_times(3)
  times5 = gen_times(5)
  times3.call(12)               #=> 36
  times5.call(5)                #=> 25
  times3.call(times5.call(4))   #=> 60


Procs are objects - they can be:

  • the returned value of a method,
  • either the key or value of a Hash,
  • arguments to other methods

The ampersand "& is used to express blocks and Procs in terms of each other (often used for arguments to methods).

Contents

Constructors: Proc.new vs. lambda

Proc instances are made from blocks via Proc.new or the lambda method. Procs created with Proc.new do not enforce arity: They may be called with more or fewer arguments than specified in the defining block. In the case of a disparity, no warning is issued: Unspecified parameters are assigned nil and superfluous arguments are ignored. Procs created with lambda raise an ArgumentError when called with the wrong number of arguments.

Proc.call(args) vs. Proc[args]

Using Procs as Blocks

Blocks, Arguments, and yield

Topics

  • Using Procs as arguments to methods
  • Using blocks as arguments to methods, including your own new methods
  • Using Procs as first-class functions
  • The inspect method
  • Nesting lambdas within other lambdas
  • The yield method
def foo
  f = Proc.new { return "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo" 
end
def bar
  f = lambda { return "return from lambda" }
  f.call # control does not leave bar here
  return "return from bar" 
end
puts foo # prints "return from foo from inside proc" 
puts bar # prints "return from bar" 


External links

Personal tools