DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Peter has posted 1 posts at DZone. View Full User Profile

Ruby Enumerated List

08.26.2007
| 3480 views |
  • submit to reddit
        Basic enumerated list in Ruby. Pass in a list of symbols. A constant is declared for each symbol and is initialized to an incremented integer value.

Use like this:
enum :FIRST, :SECOND, :THIRD

module Util
  # Basic enumerated list.
  def enum(*symbols)
    # Start out the count at 0.
    i = 0
    
    # Define a constant for each symbol in symbols, assigning it the current value
    # of i.
    symbols.each { |s| const_set(s, i);i += 1 }
  end  
end