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

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

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Ruby對象操作方法探討

有些剛剛學習編程的人員見到Ruby這個詞的是很,可能會很迷茫,不知道這是個什么東西。其實它是一種解釋型編程語言,能夠幫助我們簡便的完成許多操作。比如Ruby對象操作等等。#t#

成都創(chuàng)新互聯(lián)主要從事網(wǎng)站設計、成都網(wǎng)站制作、網(wǎng)頁設計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務。立足成都服務掇刀,10余年網(wǎng)站建設經(jīng)驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:028-86922220

Ruby不僅可以打開一個類,而且可以打開一個對象,給這個對象添加或定制功能,而不影響其他對象:

  1. a = "hello"   
  2. b = "goodbye"   
  3. def b.upcase   
  4. gsub(/(.)(.)/)($1.upcase + $2)   
  5. end   
  6. puts a.upcase #HELLO   
  7. puts b.upcase #GoOdBye   

我們發(fā)現(xiàn)b.upcase方法被定制成我們自己的了。如果想給一個對象添加或定制多個功能,我們不想多個def b.method1 def b.method2這么做我們可以有更模塊化的Ruby對象操作方式:

 
 
 
  1. b = "goodbye"   
  2. class << b   
  3. def upcase # create single method   
  4. gsub(/(.)(.)/) { $1.upcase + $2 }   
  5. end   
  6. def upcase!   
  7. gsub!(/(.)(.)/) { $1.upcase + $2 }   
  8. end   
  9. end   
  10. puts b.upcase # GoOdBye   
  11. puts b # goodbye   
  12. b.upcase!   
  13. puts b # GoOdBye   

這個class被叫做singleton class,因為這個class是針對b這個對象的。和設計模式singleton object類似,只會發(fā)生一次的東東我們叫singleton.

self 給你定義的class添加行為

 
 
 
  1. class TheClass   
  2. class << self   
  3. def hello   
  4. puts "hello!"   
  5. end   
  6. end   
  7. end   
  8. TheClass.hello #hello! 

 
self修改了你定義class的class,這是個很有用的技術(shù),他可以定義class級別的helper方法,然后在這個class的其他的定義中使用。下面一個Ruby對象操作列子定義了訪問函數(shù),我們希望訪問的時候把成員數(shù)據(jù)都轉(zhuǎn)化成string,我們可以通過這個技術(shù)來定義一個Class-Level的方法accessor_string:

 
 
 
  1. class MyClass   
  2. class << self   
  3. def accessor_string(*names)   
  4. names.each do |name|   
  5. class_eval <<-EOF   
  6. def #{name}   
  7. @#{name}.to_s   
  8. end   
  9. EOF   
  10. end   
  11. end   
  12. end   
  13. def initialize   
  14. @a = [ 1, 2, 3 ]   
  15. @b = Time.now   
  16. end   
  17. accessor_string :a, :b   
  18. end   
  19. o = MyClass.new   
  20. puts o.a # 123   
  21. puts o.b # Fri Nov 21 
    09:50:51 +0800 2008  

通過extend module的Ruby對象操作給你的對象添加行為,module里面的方法變成了對象里面的實例方法:

 
 
 
  1. Ruby代碼   
  2. module Quantifier   
  3. def any?   
  4. self.each { |x| return true 
    if yield x }   
  5. false   
  6. end   
  7. def all?   
  8. self.each { |x| return false 
    if not yield x }   
  9. true   
  10. end   
  11. end   
  12. list = [1, 2, 3, 4, 5]   
  13. list.extend(Quantifier)   
  14. flag1 = list.any? {|x| x > 5 } # false   
  15. flag2 = list.any? {|x| x >= 5 } # true   
  16. flag3 = list.all? {|x| x <= 10 } # true   
  17. flag4 = list.all? {|x| x % 2 == 0 } # false 

以上就是對Ruby對象操作的一些使用方法介紹。


文章題目:Ruby對象操作方法探討
分享網(wǎng)址:http://www.dlmjj.cn/article/dpjcidg.html