As ruby is a pure object-oriented language, everything is an object. methods are objects and classes are objects ..., therefore, self has many environments. Only by distinguishing the meanings of self in different environments can we better understand the meaning of the program.
I. Top Level Context
Ruby code
Puts self
Print out main, which indicates the default Object main.
2. In the definition of class or module:
In the definition of class and module, self represents this class or this module object:
Ruby code
Class S
Puts 'just started class s'
Puts self
Module M
Puts 'nested module S: m'
Puts self
End
Puts 'Back in the outer level of S'
Puts self
End
Output result:
Write
> Ruby self1.rb
Just started class S
Nested module S: M
S: M
Back in the outer level of S
> Exit code: 0
3. In the instance method definition:
This is the same as this in java: the object that the program automatically transmits to call this method.
Java code
Class S
Def m
Puts 'class S method m :'
Puts self
End
End
S = S. new
S. m
Running result:
Write
> Ruby self2.rb
Class S method m:
# <S: 0x2835908>
> Exit code: 0
4. In Singleton methods or class methods:
The Singleton method is a method for adding an object. Only this object owns and accesses this method. At this time, self is the object that owns this method:
Ruby code
# Self3.rb
Obj = Object. new
Def obj. show
Print 'I am an object :'
Puts "here's self inside a singleton method of mine :"
Puts self
End
Obj. show
Print 'And inspecting obj from outside ,'
Puts "to be sure it's the same object :"
Puts obj
Running result:
Write
Ruby self3.rb
I am an object: here's self inside a singleton method of mine:
# <Object: 0x2835688>
And inspecting obj from outside, to be sure it's the same object:
# <Object: 0x2835688>
> Exit code: 0
In the class method, self represents the Class Object:
Ruby code
# Self4.rb
Class S
Def S. x
Puts "Class method of class S"
Puts self
End
End
S. x
Running result:
Write
> Ruby self4.rb
Class method of class S
> Exit code: 0
From the above example, we can see that both ruby's self and java's this indicate the current or default objects that you can access in the current environment.