1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby で C言語の enum っぽく連番定数を作る

Posted at

この場合の「enumっぽい」というのは、下の C コードのように単に「整数を連番で入れた定数を作りたい」程度の意味です。

enum { // 曜日ごとに順番に 1, 2, 3, .... が割り振られる
    SUNDAY = 1,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
};

Ruby では言語としては enum は用意されていないので、通常の方法では下のように1つ1つ定数を定義することになります。

module Foo
  SUNDAY    = 1
  MONDAY    = 2
  TUESDAY   = 3
  WEDNESDAY = 4
  THURSDAY  = 5
  FRIDAY    = 6
  SATURDAY  = 7
end

曜日くらいならいいんですが、もっと大量の連番を作りたいときはこれでは大変ですね。

そんなわけで、Ruby でできるだけ手軽に enum っぽいことをする方法を考えてみました。

module Foo
  %i(
    SUNDAY
    MONDAY
    TUESDAY
    WEDNESDAY
    THURSDAY
    FRIDAY
    SATURDAY
  ).each.with_index(1){ |v, i| const_set(v, i) }
  # ruby2.7 なら { const_set(_1, _2) } でも行けますね
end

C の enum と違って途中から値を変更するということはできませんが、比較的手軽に実現できたのではないかと思います。もっとシンプルな方法があればぜひコメントお願いします。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?