日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網營銷解決方案
幾種Rubyself應用方法介紹

Ruby語言通常被人們理解為是一種解釋型腳本語言。在對Ruby語言的學習中,我們需要不斷的從編碼實踐中去總結經驗,幫助我們提高編程能力。#t#

Ruby self在不同的環(huán)境中有不同的含義,這點和java的this不同,原因是java實際上只有一種環(huán)境--在class的實例方法定義中使用,代表訪問這個方法參數(shù)自動傳進的那個對象。

而由于ruby作為一個完全純凈的面向對象語言,任何東東都是對象,方法是對象,類也是對象...,所以Ruby self就會有很多環(huán)境,區(qū)分不同環(huán)境的self含義才能更好的理解程序的含義。

一、Top Level Context

puts self

打印出main,這個代表Object的默認對象main.

二、在class或module的定義中:

在class和module的定義中,self代表這個class或這module對象:

 
 
 
  1. class S 
  2. puts 'Just started class S' 
  3. puts self 
  4. module M 
  5. puts 'Nested module S::M' 
  6. puts self 
  7. end 
  8. puts 'Back in the 
    outer level of S' 
  9. puts self 
  10. end 

輸出結果:

 
 
 
  1. >ruby self1.rb 
  2. Just started class S 
  3. Nested module S::M 
  4. S::M 
  5. Back in the outer level of S 
  6. >Exit code: 0 

三、在實例的方法定義中:

這點和java的this代表的東東一樣:程序自動傳遞的調用這個方法的對象

 
 
 
  1. class S 
  2. def m 
  3. puts 'Class S method m:' 
  4. puts self 
  5. end 
  6. end 
  7. s = S.new 
  8. s.m 

運行結果:

 
 
 
  1. >ruby self2.rb 
  2. Class S method m: 
  3. # 
  4. >Exit code: 0 

四、在單例方法或者類方法中:

單例Ruby self方法是針對一個對象添加的方法,只有這個對象擁有和訪問這個方法,這時候self是擁有這個方法的對象:

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

運行結果:

 
 
 
  1. ruby self3.rb 
  2. I am an object: here's self 
    inside a singleton method of mine: 
  3. # 
  4. And inspecting obj from outside,
     to be sure it's the same object: 
  5. # 
  6. >Exit code: 0 

在類方法中Ruby self代表這個類對象:

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

運行結果:

 
 
 
  1. >ruby self4.rb 
  2. Class method of class S 
  3. >Exit code: 0 

從上面的例子我們可以看出不管是Ruby self還是java的this都表示在當前的環(huán)境下你可以訪問的當前的或者默認的對象。


分享標題:幾種Rubyself應用方法介紹
URL標題:http://www.dlmjj.cn/article/cdcdepd.html