LoginSignup
1
1

More than 5 years have passed since last update.

Ruby で C言語ライクな enum を行うライブラリをつくった

Posted at

ブログ記事からの転載です。実装があれなので書き直したい

Ruby で C言語ライクな enum をするライブラリをつくった。

インストール

$ gem install cstyle_enum

使い方

require "cstyle_enum"

class Color
    # enum or cstyle_enum
    Colors = enum {
        RED
        GREEN = 3
        BLUE
    }
end

Color::RED     # => 0
Color::GREEN   # => 3
Color::BLUE    # => 4
Color::Colors  # => {:RED=>0, :GREEN=>3, :BLUE=>4}

#enum のブロック内に定数を記述すると自動的にナンバリングされた定数が定義されます。

C言語と同様に = で代入すればその値から続けてナンバリングされます。

また #enum の戻り値は定義した定数の Hash が返ってきます。

ユーザコードはかなり書きやすくなっているんですが、実装がかなり闇になってる…。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1