Ruby Definition of Self

前端 未结 3 1941
感动是毒
感动是毒 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:35

    self is a special variable that changes depending on the context. To be more specific, it is receiver object of the current method, as you mentioned. To understand this, we need to understand what receiver means.

    See Programming Ruby: More About Methods and Classes and Objects.

    You call a method by specifying a receiver, the name of the method, and optionally some parameters and an associated block.

    connection.downloadMP3("jitterbug") { |p| showProgress(p) }
    

    In this example, the object connection is the receiver, downloadMP3 is the name of the method, "jitterbug" is the parameter, and the stuff between the braces is the associated block.

    foo = "hello"
    bar = foo.dup
    class <

    In foo.twoTimes, foo part is called the receiver of the method call. So, within the twoTimes method, self refers to the object foo in the context.

    There is also a very good explanation here

提交回复
热议问题