幾種Ruby self應(yīng)用方法介紹
Ruby語言通常被人們理解為是一種解釋型腳本語言。在對Ruby語言的學(xué)習(xí)中,我們需要不斷的從編碼實踐中去總結(jié)經(jīng)驗,幫助我們提高編程能力。#t#
Ruby self在不同的環(huán)境中有不同的含義,這點和java的this不同,原因是java實際上只有一種環(huán)境--在class的實例方法定義中使用,代表訪問這個方法參數(shù)自動傳進的那個對象。
而由于ruby作為一個完全純凈的面向?qū)ο笳Z言,任何東東都是對象,方法是對象,類也是對象...,所以Ruby self就會有很多環(huán)境,區(qū)分不同環(huán)境的self含義才能更好的理解程序的含義。
一、Top Level Context
puts self
打印出main,這個代表Object的默認(rèn)對象main.
二、在class或module的定義中:
在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
輸出結(jié)果:
- >ruby self1.rb
- Just started class S
- Nested module S::M
- S::M
- Back in the outer level of S
- >Exit code: 0
三、在實例的方法定義中:
這點和java的this代表的東東一樣:程序自動傳遞的調(diào)用這個方法的對象
- class S
- def m
- puts 'Class S method m:'
- puts self
- end
- end
- s = S.new
- s.m
運行結(jié)果:
- >ruby self2.rb
- Class S method m:
- #<S:0x2835908>
- >Exit code: 0
四、在單例方法或者類方法中:
單例Ruby self方法是針對一個對象添加的方法,只有這個對象擁有和訪問這個方法,這時候self是擁有這個方法的對象:
- # 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
運行結(jié)果:
- 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
在類方法中Ruby self代表這個類對象:
- # self4.rb
- class S
- def S.x
- puts "Class method
of class S"- puts self
- end
- end
- S.x
運行結(jié)果:
- >ruby self4.rb
- Class method of class S
- >Exit code: 0
從上面的例子我們可以看出不管是Ruby self還是java的this都表示在當(dāng)前的環(huán)境下你可以訪問的當(dāng)前的或者默認(rèn)的對象。