0

I want to get the constants defined in my scripts, suppose I have two files like this:

script_two.rb

TWO = 'this is 2'

script_one.rb

require_relative 'script_two'

ONE = 'this is 1'
# Check for constants

I want to know how to get the array of constants [ONE, TWO] (order doesn't matter).

I know that Object.constants gives an array of current constants but that includes lots of other constants like TRUE, NIL, etc.

I thought of keeping the result of that at the beginning and then call it again after requires so I can make the difference. But it's a bit ugly, isn't there another way?

Redithion
  • 986
  • 1
  • 19
  • 32
  • Possible duplicate of [Does Ruby provide a constant\_added hook method?](http://stackoverflow.com/questions/17407908/does-ruby-provide-a-constant-added-hook-method) – phoet Feb 07 '17 at 16:31
  • I don't see it as a duplicate, but it's related. The main difference is that I don't want a hook or get all constants I just want **my** constants – Redithion Feb 07 '17 at 17:37

1 Answers1

3

This is tricky because not having a class your are putting your constants onto the main:Object when you run your script. So you need to be able to know what constants are defined before the script executes. Something like this would work:

#script_one.rb
obj_cons = Object.constants
require_relative 'script_two'

ONE = 'this is 1'
puts self.class.constants - obj_cons

That generates the array: [TWO, ONE] -- which I believe is what you want.

$ ruby script_one.rb
TWO
ONE
Nicholas C
  • 1,103
  • 1
  • 7
  • 14