Ruby method, Proc, and block confusion

前端 未结 3 1203
春和景丽
春和景丽 2021-02-07 01:04

I have a couple questions about Ruby\'s methods, procedures, and blocks that strike me as rather odd. They\'re not so much about syntax or function as the logic behind the deci

相关标签:
3条回答
  • 2021-02-07 01:20

    Question 1: Blocks are not objects, they are syntactic structures; this is why they cannot be assigned to a variable. This is a privilege reserved for objects.

    Question 2: Methods are not objects, so they cannot receive messages. Inversely, procs and lambdas are objects, so they cannot be invoked like methods, but must receive a message that tells them to return a value on the basis of the parameters passed with the message.

    Procs and Lambdas are objects, so they can receive the call message and be assigned to names. To summarize, it is being an object that makes procs and lambdas behave in ways you find odd. Methods and blocks are not objects and don't share that behavior.

    0 讨论(0)
  • 2021-02-07 01:23

    Methods are methods — that is, they're actions that an object can take in response to messages. They are not functions.

    Blocks are closures — they're functions that close over the enclosing scope. They don't conceptually "belong to" a given object.

    In some languages, methods are merely functions that are members of an object, but Ruby does not view them this way. Separating a method from its owning object is more akin to surgery than simple assignment. Ruby takes its object-orientation model from Smalltalk, the granddaddy of modern OO.

    0 讨论(0)
  • 2021-02-07 01:27

    To some extent at least, methods are objects:

    class ABC
      def some_method
      end
    end
    ABC.instance_method(:some_method) #=> #<UnboundMethod: ABC#some_method>
    

    Further to that, there is a built-in class: Method, as documented here.

    See also this: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls

    Haphazardly <bseg>, it does rather seem to bear out the everything-is-an-object thing. In this particular case, it just appears to take a little more digging to see.

    (I really must make an effort to understand this better: I'm starting to think it's fundamental to getting a deeper understanding.)

    0 讨论(0)
提交回复
热议问题