This post originated from an RSS feed registered with Ruby Buzz
by Jamis Buck.
Original Post: Enumerated types in Ruby
Feed Title: the buckblogs here
Feed URL: http://weblog.jamisbuck.org/blog.cgi/programming/index.rss
Feed Description: Jamis Buck's corner of the blogging universe. Mostly about ruby, but includes ramblings on a variety of topics.
It’s not often that I need an enumerated type in Ruby—there is usually a more elegant way of doing things, I’ve found. But when I’m interfacing with a C library (such as fmod, in this case), it can be a pain to stop and define constants for every enumerated type.
It’s probably been done before, but I found the following little class quite helpful:
class EnumeratedType
class <<self
def start(n)
@next_value = n
end
def const_missing(sym)
@next_value ||= 0
const_set(sym, @next_value)
@next_value += 1
end
end
end
It lets you create enumerated types like this:
class OutputType < EnumeratedType
AUTODETECT
UNKNOWN
NOSOUND
WAVWRITER
DSOUND
WINMM
ASIO
OSS
ALSA
ESD
SOUNDMANAGER
COREAUDIO
XBOX
PS2
GC
XBOX360
PSP
end
If you want to start with a different integer than 0, you can just do:
class OutputType < EnumeratedType
start 15
AUTODETECT
...
end
You can also use start anywhere in the list, to have subsequent constants enumerated starting with the given value.