Ruby functions vs methods

前端 未结 3 1487
小蘑菇
小蘑菇 2020-12-14 01:27

In the Ruby Programming Language, Chapter 6 (second paragraph) they state:

Many languages distinguish between functions, which have no associated

3条回答
  •  悲&欢浪女
    2020-12-14 01:51

    lambdas in Ruby are objects of class Proc. Proc objects don't belong to any object. They are called without binding them to an object.

    Methods are objects of either class Method or UnboundMethod, depending on whether they're bound or unbound. See the explanation here. Unbound methods can't be called until they're bound to an object.

    lambda{|x| x}.class      # => Proc
    lambda{|x| x}.call(123)  # => 123
    
    class Foo
      def bar(baz)
        baz
      end
    end
    
    puts Foo.new.method(:bar).class     # => Method
    puts Foo.new.method(:bar).call(123) # => 123
    
    puts Foo.instance_method(:bar).class     # => UnboundMethod
    puts Foo.instance_method(:bar).call(123) # => throws an exception
    

    You can bind an UnboundMethod to an object and then call it. But you can't bind a Proc to an object at all. Proc objects can however capture local variables in the surrounding scope, becoming closures.

提交回复
热议问题