Looking at the code from
here:Learn How to Blog and Build Websites for Profit!
I copied the Const class into my test module, and bolted it inside a
method. This then caused me a smallish problem, as I then received an
error when trying to set the constants from within a method.
After googling a bit, I found that I could set the constants from within
a method by using the ‘class.const_set’ method - as:
CONST = OUTER_CONST + 1
STDOUT.puts "Constants Test (Const Is) : "+defined? Const
STDOUT.puts "Constants Test (Const.new.get_const):
STDOUT.puts "Constants Test (Const::CONST): "+Const::CONST.to_s
STDOUT.puts "Constants Test (::OUTER_CONST): "+::OUTER_CONST.to_s
# Odd, I can set a constant (or even create a new one) like this
# But the following line throws a constant redef error
#STDOUT.puts “Constants Test : (Const::NEW_CONST = 345
)”+(Const::NEW_CONST = 345).to_s
STDOUT.puts “Constants Test :
What I’m then confused about is really two things:
Why is it allowable to in effect modify a class? I can follow
extending a class and adding additional features etc (although I haven’t
got that far yet) - but I don’t quite grasp the concept of
Const::NEW_CONST = value.
I thought everything was in a method anyway - but why is it not
allowed to do something like Const::NEW_CONST = value from within a
method, but then allow Const.const_set(“CONSTANT”, value)?