Wednesday, February 1, 2012

An Introduction to Procs, by Peter Cooper

I have just watched the 27-min introduction on Procs by Peter Cooper, which is really a short section of his RubyReloaded course.



Here are my notes:
  • blocs are essentially nameless functions
  • the block_given? method can be used to find out if a block was passed to the current scope
  • blocks are anonymous functions which can be passed around and called at will
  • one can only pass a single block to a method, but one can pass multiple procs around (as arguments of a method)
  • Proc.new will create a Proc object if there was a block passed in the current context (otherwise it will raise an error)
  • In Ruby 1.9, there are 4 ways to call (or run) proc objects:

my_proc = Proc.new do |e|
    puts "this is #{e}"
end

my_proc.call(2)
my_proc.(2)
my_proc[2]
my_proc === 2

  • a lambda is a proc object which respects argument arity, much like an anonymous method
  • in 1.8, "proc" (surprisingly) created a lambda (and not a Proc object)
  • in 1.9, "proc" is the same as doing Proc.new (as we would expect)
  • a return in a proc will try to return from the context where the proc was defined (and not from where it is executed)
  • in a closure, ruby keeps references to variables. You can thus modify a variable's value inside a proc even after the proc was defined. Thus this code will output "Marc":
def run_proc(p)
  p.call
end

name = "Fred"
my_proc = proc { puts name }
name = "Marc"
run_proc my_proc

No comments: