Issue
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?
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 > meth_ref.call(2,3)
Proc Object:
a = lambda {|a, b| puts "#{a}, #{b}"}
a.call(2,3)
Solution
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.
Answered By - user513951 Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.