新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Rubynil概念詳解
Ruby語言在實際應(yīng)用中可以幫助我輕松的解決許多問題。在這里我們將會為大家詳細解讀有關(guān)Ruby nil的一些概念,希望能對大家的學(xué)習(xí)有些幫助。#t#

我們常常處理這樣的代碼:
name=person?person.name:nil
取某個對象的一個屬性,先判斷對象是否為nil,不是Ruby nil就返回對象屬性,否則返回nil。這樣的代碼寫多了比較惡心,是否有比較有趣的方式來減少代碼?作者給出了一段代碼:
- module ObjectExtension
- def nil_or
- return self unless self.nil?
- o = Object.new
- class << o
- def method_missing(sym,
*args); nil; end- end
- o
- end
- end
- class Object
- include ObjectExtension
- end
上面的代碼為Object加入了擴展,為每個對象實例增加了一個nil_or方法,分析下這個方法:如果對象不為Ruby nil,馬上返回self(也就是對象本身),否則生成一個新的對象,這個對象通過method_missing機制將所有的方法調(diào)用都返回nil(原文是用Class.new,生成的類將不會被GC,這里采用回復(fù)給出的方案,生成對象,在對象的metaclass上做method_missing)。那么現(xiàn)在代碼可以寫成:
name=person.nil_or.name是不是相當(dāng)?shù)腄SL呢?
文章題目:Rubynil概念詳解
網(wǎng)址分享:http://www.5511xx.com/article/dhhhcdi.html


咨詢
建站咨詢
