Ruby Definition of Self

前端 未结 3 1942
感动是毒
感动是毒 2020-12-03 00:14

I was reading a Ruby book and came across this definition of the pseudo-variable self:

self - receiver object of the current method

3条回答
  •  广开言路
    2020-12-03 00:40

    self - receiver object of the current method

    "Method calling" in Ruby is accomplished through a message-sending mechanism. So

    some_object.some_method(args)
    

    is a shorthand for

    some_object.send(:some_method, args)
    

    I think this is what the quote is referring to: "self" is the object to which the message (or method) has been sent: the receiver of the current method.

    The whole message-sending thing is part of what makes Ruby so dynamic. It makes it easy for an object to define method_missing for messages it doesn't currently handle and decide what to do with them. Rails uses this a lot: ActiveRecord, for example has the "find_by..." syntax, which figures out what's wanted from the name of the method called/sent.

提交回复
热议问题