The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Enumerated types in Ruby

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jamis Buck

Posts: 184
Nickname: minam
Registered: Oct, 2004

Jamis Buck is a C/Java software developer for BYU, and hacks in Ruby for fun.
Enumerated types in Ruby Posted: Aug 7, 2005 11:32 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jamis Buck
Latest Posts From the buckblogs here

Advertisement

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.

Read: Enumerated types in Ruby

Topic: New blog Previous Topic   Next Topic Topic: David is the

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use