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