Redithion Redithion - 2 years ago 57
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:


TWO = 'this is 2'


require_relative 'script_two'

ONE = 'this is 1'
# Check for constants

I want to know how to get the array of constants
(order doesn't matter).

I know that
gives an array of current constants but that includes lots of other constants like
, 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:

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