On 05.02.2007 20:54, Dan Stevens (IAmAI) wrote:
> It seems to me that I should simply be able to use symbols as values
> for my enumerated types, like for example:
> 
> class Color
> 
>  def initialize(color)
>    @color = color
>  end
> 
>  def to_hex
>    case @color
>      when :red: 0xFF0000
>      when :green: 0x00FF00
>      when :blue: 0x0000FF
>      else @color
>    end
>  end
> 
> end
> 
> c = Color.new(:red)
> puts c.to_hex.to_s(16)
> 
> Might there be any reason why I shouldn't do this, or am I quite fine
> doing this?

That's perfectly ok.  If you need your enums only for mapping then I'd 
probably do this:

Color = Struct.new :name do
   CODES = Hash.new {|h,k| k}.update(
     :red => 0xFF0000,
     :green => 0x00FF00
     # ...
   )

   def to_hex; CODES[name] end
end

irb(main):010:0> Color.new(:red).to_hex.to_s 16
=> "ff0000"

If you need more enum dependent behavior you might want put more complex 
objects into the hash instead of only Fixnums.

Kind regards

	robert