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)
A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.
When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.
In Ruby, a lambda is an object similar to a proc. Unlike a proc, a lambda requires a specific number of arguments passed to it, and it return s to its calling method rather than returning immediately. proc_demo = Proc. new { return "Only I print!" }
A proc is an object that contains a code block. It provides a way to save up a code block and execute it later. A lambda is special kind of proc (more on that later).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With