Ruby Const_defined?
Ruby const_defined?
今天看專案的時候,看到一段
return self.class::ABC if self.class::const_defined?(:ABC)
後來到 apidock 看了一下,原文大概是查看 mod 或是祖先裡面是否已經定義常數名稱
const_defined?(*args) public
Says whether mod or its ancestors have a constant with the given name
下面是網站的範例 :
Float.const_defined?(:EPSILON) # true, found in Float itself
Float.const_defined?("String") # true, found in Object (ancestor)
BasicObject.const_defined?(:Hash) # false
然後如果在 classes 或是 Modules 裡面撿查中,發現常量不存在但是有自動加載,會直接回傳 true 但是不會自動加載
module Admin
autoload :User, 'admin/user'
end
Admin.const_defined?(:User) # true

留言
張貼留言