Rubyでenum (列挙型)を使いたいときには、クラスでそれらしいものを作ることができます。
- 実装
class Weather
RAINY = "RAINY"
CLOUDY = "CLOUDY"
SUNNY = "SUNNY"
class << self
def rainy
@rainy ||= Weather.new(RAINY)
end
def cloudy
@cloudy ||= Weather.new(CLOUDY)
end
def sunny
@sunny ||= Weather.new(SUNNY)
end
end
def initialize(weather_str)
@weather_str = weather_str
end
# 等価演算子==をオーバーライドするためにto_sを定義しています
def to_s
@weather_str
end
# ifやcaseで条件分岐できるようにオーバーライドしています
def ==(weather)
to_s == weather.to_s
end
end
- 利用
weather = Weather.sunny
pp "Today is sunny!!" if weather == Weather.sunny