On Mar 8, 2006, at 8:34 PM, Jeff Cohen wrote:

> Stephen Waits wrote:
>> I explained that each symbol has a unique ID, and that Ruby uses  
>> symbols
>> to look stuff up within its own system.  I believe I had given them
>> several ".send(:symbol)" examples at that point.
>
> And it's much better than the "it's an immutable string" explanation,
> which I've found to be just a rats nest of problems.
>
> Enums are another good analogy.  But in C++/C# enums are typed so you
> know the client gave you a valid value.  The only way I can see to
> enforce this in Ruby is to create a constant array of the valid  
> symbols
> and then make sure what they passed me is in the array:
>
>

Enums are typed in C++, to a certain extent (better than C anyway),  
but if the lhs is an int well...


> Somehow I feel this is pretty un-rubylike, to have to have that if
> statement in front of every method.  Any idea if there's a more
> ruby-like way to have enum-like behavior?
>
> Thanks
> Jeff
>
> -- 
> Posted via http://www.ruby-forum.com/.
>

The idiom I usually use is:
class HockeyGear
       Stick = Object.new
       Helmet = Object.new
       ...etc...
end

Of course other than the aesthtics of looking like an enum  
(HockeyGear::Stick) in the source code  there's no advantage over  
symbols. On the other hand, if someone is passing you an enum, it  
probably means any one of the enums is valid, so you should be  
checking all of them anyway, and throw an exception in the else  
clause. Checking whether an object is of  the right type isn't very  
ruby-like anyway.