Hi --

On Tue, 14 Jul 2009, Buzz Hill wrote:

> 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

-- 
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to