ruby语言里的self理解

关键的一句话:关键看谁调用self,self就属于谁

有3种情况:

1、在class或module的定义中,self代表这个class或者这个module对象,代码如下:

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

输出结果:

Just started class S
S
Nested module S::M
S::M
Back in the outer level of S
S

2、在实例方法中,self代表调用方法的对象,对象实际上是内存里的一块内存空间,例如:

class S  
   def m  
        puts 'Class S method m:'  
        puts self  
    end  
end  
s = S.new  
s.m 

输出结果如下:

1 Class S method m:
2 #<S:0x2bc0a10>

3、在单例方法中,是为一个对象设置的函数,所以此时的self代表的是拥有这个方法对象,例如:

 1 obj = Object.new  
 2 def obj.show  
 3   print 'I am an object: '  
 4   puts "here's self inside a singleton method of mine:"  
 5   puts self  
 6 end  
 7 obj.show  
 8 print 'And inspecting obj from outside, ' 
 9 puts "to be sure it's the same object:"  
10 puts obj  

其中,Object是最大的一个类,不需要再定义了,所以这里就省略了class部分对Object的定义。

输出结果为:

1 I am an object: here's self inside a singleton method of mine: 
2 #<Object:0x2835688>   #这里就是对象所占的内存地址
3 And inspecting obj from outside, to be sure it's the same object: 
4 #<Object:0x2835688>

4、在类方法中,self代表的是类本身

1 class S  
2   def S.x  
3     puts "Class method of class S"  
4     puts self  
5   end  
6 end  
7 S.x  

运行结果如下:

1 Class method of class S
2 S
原文地址:https://www.cnblogs.com/fish-101/p/10311402.html