Redithion Redithion - 1 year ago 53
Ruby Question

Is there a way to get only the constants defined by my script?

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download