enums 1.0 library / gem - safe enumeration types for ruby e.g. enum :Color, [:red, :green, :blue]

Gerald Bauer <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAAxEZd_SjDx0M8x5ssN=b6iTwgqJ53B6S7YOg=j0DQh69S8XsQ@mail.gmail.com>
Hello,

   I've put together a new enums library / gem [1] for safe
enumeration types in ruby.

Yes, enums are just a set of symbolic keys bound to unique integer numbers.
Why not just use symbols :-) or constants? Do we really need a new enum type
and (yet another) library? Good point.

  Let the ruby meta-programming magic work for you :-).

    Enum.new( 'Color', :red, :green, :blue )   # -or-

    enum :Color, :red, :green, :blue    # -or-

    enum :Color, [:red, :green, :blue]

  See what you get for "free":

    Color::RED           #=> <Color @key=:red, @value=0>
    Color(0)             #=> Color::RED -or- <Color @key=:red, @value=0>
    Color.zero           #=> same as Color(0)
    Color.red            #=> Color::RED
    Color.values         #=> [0, 1, 2]
    Color.keys           #=> [:red, :green, :blue]
    Color.members        #=> [RED, GREEN, BLUE]
                         #    -or-
                         #   [<Color @key=:red,   @value=0>,
                         #    <Color @key=:green, @value=1>,
                         #    <Color @key=:blue,  @value=2>]
    Color(1)             #=> Color::GREEN
    Color.value(1)       # same as Color(1)
    Color[:red]          #=> Color::RED
    Color.key(:red)      # same as Color[:red]
    color = Color.red
    color.red?           #=> true
    color == Color.red   #=> true
    color.value          #=> 0
    color.key            #=> :red
    color.blue?          #=> false
    color == Color.blue  #=> false
    color.is_a? Enum     #=> true
    color.is_a? Color    #=> true

   and some more.

  Questions? Comments? Welcome. Cheers. Prost.

PS: The new enums 1.0 library is part of the safe data structures series. [2]

[1] https://github.com/s6ruby/enums
[2] https://github.com/s6ruby/safestruct

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.