Hi --
Marnen Laibow-Koser wrote:
When you are confused about something, it is sometimes hard to distill
all your thoughts down to the essence of the issue and ask the right
question. But I am trying to define a CONSTANT using the result of an
instance method
No you're not. The constant you're trying to define is clearly a class
property.
If you think about it, this is as it should be. The constant is going
to have the same value for every instance of the class. In other words:
a = PaymentType.new
b = PaymentType.new
a and b are now separate instances of PaymentType -- but surely you
never want a.PAYMENT_TYPES to be different from b.PAYMENT_TYPES ?
The syntax of a.PAYMENT_TYPES won't work. I am not sure if you meant it
to work or you were just using it for the sake of explanation.
The syntax will work if you've got an instance method called
PAYMENT_TYPES, but if you don't, it will fail -- whether or not you
have a constant called PAYMENT_TYPES.
But I get your point, which has enhanced my understanding. Things that
relate to the class in general, things that shouldn't be redefined, like
Math:PI are controlled only by class methods. So, in the above example,
if the payment_types were to change dynamically as the program executed,
I would not use a constant, I would setup getter and setter methods.
I think you're overthinking it. There's no inherent connection between
constants and class methods.
module MyMathModule
PI = 3.14159265358979
end
puts "PI is #{MyMathModule::PI}"
I've created a module and a constant inside that module. The constant
is resolved using the :: operator, and no methods are involved.
If you define an instance method, you can use the class's constants:
class Rainbow
COLORS = %w{ red orange yellow green blue indigo violet }
def show_me_the_colors
puts "My colors are: #{COLORS.join(", ")}"
end
end
r = Rainbow.new
r.show_me_the_colors
=> My colors are: red, orange, yellow, green, blue, indigo, violet
David