RobJ
RobJ

Reputation: 129

If a Ruby constant is defined, why isn't it listed by constants()?

Class names seem to show up when you check for them with const_defined?() but not when you try to list them with constants(). Since I'm interested in listing any defined class names, I'm just trying to work out what's going on. Example:

class MyClass
  def self.examine_constants
    puts self.name
    puts const_defined? self.name
    puts constants.inspect
  end
end

MyClass.examine_constants

Under Ruby 2.0.0p195, that code gives the following results:

MyClass
true
[]

Shouldn't the methods agree? What am I missing please?

Upvotes: 1

Views: 193

Answers (1)

fmendez
fmendez

Reputation: 7338

The Module#constant method you're using return all the constants at the current scope. What you might want to use is the class method Module.constant which returns all the top-level constants. For instance:

class MyClass
  def self.examine_constants
    puts self.name
    puts const_defined? self.name
    puts Module.constants.inspect
  end
end

MyClass.examine_constants

Response:

MyClass
true
[...lots of other constants, :MyClass]

Upvotes: 2

Related Questions