Ruby處理方法調用中的nil

來源:互聯網
上載者:User

我們常常處理這樣的代碼:

name=person?person.name:nil

取某個對象的一個屬性,先判斷對象是否為nil,不是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方法,分析下這個方法:如果對象不為nil,馬上返回self(也就是對象本身),否則產生一個新的對象,這個對象通過method_missing機制將所有的方法調用都返回nil(原文是用Class.new,產生的類將不會被GC,這裡採用回複給出的方案,產生對象,在對象的metaclass上做method_missing)。那麼現在代碼可以寫成:

name=person.nil_or.name是不是相當的DSL呢?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.