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

I know that methods in Ruby are not objects, but procs and lambdas. Is there any difference between them other than this? Because we can get along. What makes 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) 
+9
source share
2 answers

In short, the Method object is “associated” with the object, so self points to this object when the method is call , and Proc does not have this behavior; self depends on the context in which Proc was created / invoked.

Anyway:

In your question, you said that “methods are not objects,” but you must be careful to distinguish between “method” and “ Method .

A "method" is a specific set of expressions that are named and placed in the method table of a particular class to simplify the search and execution later:

 class Foo def my_method puts "line 1" puts "line 2" end end 

The Method object (or similarly the UnboundMethod object) is a real Ruby object created by calling method / instance_method / etc. And passing the name of the "method" as an argument:

 Foo.new.method(:my_method) # => #<Method: Foo#my_method> Foo.instance_method(:my_method) # => #<UnboundMethod: Foo#my_method> 

A Proc object is a collection of expressions that are not given a name that you can save for later execution:

 my_proc = Proc.new { 123 } my_proc.call # => 123 

It may be useful to read the UnboundMethod documentation for UnboundMethod , Method and Proc . The RDoc pages list the various instance methods available for each type.

+6
source

Differences between blocks and procs

  • Procs are objects, blocks are not
  • No more than one block can be displayed in the argument list

Differences between procs and lambdas

  • Lambdas checks the number of arguments, while procs do not
  • Lambdas and procs relate to return keyword differently

This is very well explained here (I just copied it from the link below)

http://awaxman11.imtqy.com/blog/2013/08/05/what-is-the-difference-between-a-block/

+2
source

Source: https://habr.com/ru/post/1208479/


All Articles