What is the difference between a method and a proc object?
Differences between blocks and procs
- Procs are objects, blocks are not
- At most one block can appear in an argument list
Differences between procs and lambdas
- Lambdas check the number of arguments, while procs do not
- Lambdas and procs treat the
return
keyword differently
It is very well explained here (I just copied that from the link below)
http://awaxman11.github.io/blog/2013/08/05/what-is-the-difference-between-a-block/
In brief:
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.
However:
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:
class Foo
def my_method
return 123
end
end
Foo.new.my_method
# => 123
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:
my_Foo = Foo.new
my_Method = my_Foo.method(:my_method)
# => #<Method: Foo#my_method>
my_Method.call
# => 123
my_UnboundMethod = Foo.instance_method(:my_method)
# => #<UnboundMethod: Foo#my_method>
my_UnboundMethod.bind(my_Foo).call
# => 123
A Proc
object is a set of expressions that is not given a name, which you can store for later execution:
my_proc = Proc.new { 123 }
my_proc.call
# => 123
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.