實際上,我在 NodeJS 方面經驗豐富,但我對 Ruby 很陌生,我無法理解這段 ruby?? 代碼是如何作業的,有人能解釋一下這段 Ruby 代碼中的self.call方法和self.[]方法到底在做什么嗎?
1. class Mine::Container
2.
3. def self.call
4. @containers || {}
5. end
6.
7. def self.[] namespace
8. @containers ||= Hash.new{|h, k| h[k] = new }
9. @containers[namespace]
10. end
11.end
究竟self.call,self.[]方法在做什么?如果我打電話,我會得到什么Mine::Container.().?
uj5u.com熱心網友回復:
Mine::Container.()是一個快捷方式,Mine::Container.call這意味著它會呼叫如下所示的call類方法:
def self.call
@containers || {}
end
它回傳@containersif @containersis set 的值,否則(如果@containersis not nilor false)回傳一個空哈希({})。
此外,def self.[] namespace定義了一個類方法來期望一個namespace可以像這樣呼叫的引數:
Mine::Container[namespace]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445702.html
上一篇:處理意外資料庫Nils的最佳方法
