:symbol vs CONSTANT choice

I have a list of about 12 items that I wish to repeatedly store as part
of a record in a file. The obvious way to do this is to define a bunch
of constant terms with values [1 … 12]. But when I want to use them in
the program, symbols would be more convenient. Is there a better way to
do this than just defining the constants, and using a pair of functions
to convert to and from symbols?

On Thu, Aug 16, 2012 at 11:37 PM, Charles H.
[email protected] wrote:

I have a list of about 12 items that I wish to repeatedly store as part of a
record in a file. The obvious way to do this is to define a bunch of
constant terms with values [1 … 12]. But when I want to use them in the
program, symbols would be more convenient. Is there a better way to do this
than just defining the constants, and using a pair of functions to convert
to and from symbols?

There are some approaches to do enums in Ruby out there, e.g.

http://www.lesismore.co.za/rubyenums.html

You’ll find plenty more with your favorite search engine.

Other than that the two function approach probably works as well. Or
you use two Hashes for both directions and not two functions.

Kind regards

robert

On 08/17/2012 07:50 AM, Robert K. wrote:

There are some approaches to do enums in Ruby out there, e.g.

robert

Thanks. I pulled two versions of enum out of those links, that look
like they might be what I want. It will be a couple of weeks yet, and I
don’t know whether the bit manipulation version (class) will be what I
need or whether I’ll go with the simpler (module) version. One of them
will clearly be more suited to the situation than just defining a bunch
of constants.

Of course, since I don’t need anything this general, I could just
define a class with a bunch of read accessors to class level variables,
and no write accessor. Initialize them with constant values. …
Well, it would work, but it feels really sloppy. With the enum methods
I can add a to_s that does what I want, and a to_i that does what I
want, so I could store them cheaply in a database, and print them out in
a meaningful form. (This means I don’t want to exactly use either of
the two best solutions you pointed me at, but a customized variation.
But that’s relatively a small change.)