LoginSignup
1
0

[Ruby] enumを使いたい!!

Last updated at Posted at 2024-03-19

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

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