2014-01-20 107 views
0

我想初始化一個常量,如果它不存在,如果已經存在,然後使用它。我嘗試了下面的警告。如何處理初始化常量?

User = User || Struct.new(:name) #NameError: uninitialized constant User 
User = Struct.new(:name) || User #works (1st time) 

但這句話會遇到多次,這種情況發生時,我得到

User = Struct.new(:name) || User 

#warning: already initialized constant User 
#warning: previous definition of User was here 

如何處理這種情況?

回答

2

試試這個

User ||= Struct.new(:name) 

User = User || Struct.new(:name)這是行不通的,因爲User正與條件運算||定義它前檢查。因此,您得到的錯誤爲NameError:未初始化的常量用戶。例如

# first try that way 
X = X || 2 #uninitialized constant X (NameError) 
# then comment the above and try below way 
X ||= 2 
X # => 2 

X = X || 2將無法​​正常工作,因爲我們沒有使用它與||之前的任何地方定義它。

+0

啊哈,我覺得'a || = b'等於'a = a || b' – Bala

+0

@Bala不,它不是..我明白, –