This is me This is me - 1 month ago 4
Ruby Question

What is the difference between a method and a proc object?

I know that methods in Ruby are not objects but procs and lambdas are. Is there any difference between them other than that? Because both we can pass around. What makes the proc objects different from a method?


1.8.7-p334 :017 > def a_method(a,b)
1.8.7-p334 :018?> puts "a method with args: #{a}, #{b}"
1.8.7-p334 :019?> end
1.8.7-p334 :021 > meth_ref = Object.method("a_method")
=> #<Method: Class(Object)#a_method>
1.8.7-p334 :022 >,3)

Proc Object:

a = lambda {|a, b| puts "#{a}, #{b}"},3)


You said in your question that "methods are not objects" but you have to be careful to distinguish between "method" and "Method".

A "method" is a defined set of expressions that is given a name and put into the method table of a particular class for easy lookup and execution later.

A "Method" object (or similarly an "UnboundMethod" object) is an actual Ruby object created by calling method / instance_method / etc. and passing the name of a "method" as the argument.

You may find it useful to read the RDoc documentation for UnboundMethod, Method, and Proc. The RDoc pages list the different instance methods available to each type.

Basically, a Method object is "bound" to an object so that self points to that object when you call the method, and a Proc doesn't have that behavior; self depends on the context in which the Proc was created/called.