Check if a constant is already defined

后端 未结 3 1899
故里飘歌
故里飘歌 2020-12-09 00:45

This is a simple one, I hope. How do I check, in the following example, if a constant is already defined?

#this works
var = var||1
puts var
var = var||2
put         


        
相关标签:
3条回答
  • 2020-12-09 00:59
    CONST = 2 unless defined? CONST
    

    See here for more about awesome defined? operator.

    P.S. And in the future I guess you'll want var ||= 1 instead of var = var||1.

    0 讨论(0)
  • 2020-12-09 01:02
    CONST ||= :default_value
    

    the above works for me on ruby 1.9.3 but fails on 1.8... well 1.8 is ancient now.

    0 讨论(0)
  • 2020-12-09 01:16

    const_defined? API

    pry> User.const_defined?("PER_PAGE")
    => true
    pry> User.const_defined?("PER_PAGE123")
    => false
    
    0 讨论(0)
提交回复
热议问题