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:
class Const
def get_const
CONST
end
CONST = OUTER_CONST + 1
end
def constants_test
STDOUT.puts "Constants Test (Const Is) : "+defined? Const
STDOUT.puts "Constants Test (Const.new.get_const):
"+Const.new.get_const.to_s
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
line
Const.const_set(“NEW_CONST”, 234)
# 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 :
(Const::NEW_CONST)”+Const::NEW_CONST.to_s
end
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)?