Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

"<=>"メソッドのオーバーライドによる比較の実装

名著"Effective Ruby"に「"<=>"とComparableモジュールで比較を実装しよう」と書いてあったので江戸時代の身分制度を実装してみた。

class Rank
  include Comparable
  attr_reader :name
  NAMES = ['士', '農', '工', '商'].map(&:freeze).freeze

  def initialize(name)
    unless NAMES.include?(name)
      raise(ArgumentError, "Argument must be any of #{NAMES}")
    end
    @name = name
  end

  def <=> (other)
    NAMES.index(self.name) <=> NAMES.index(other.name)
  end
end
['農', '工', '士', '商'].map{|s| Rank.new(s)}.sort.map{|rank| rank.name} 
# => ["士", "農", "工", "商"]

Rank.new('農')  < Rank.new('商')  # => true
Rank.new('農')  > Rank.new('商')  # => false
Rank.new('士') == Rank.new('士')  # => true
Rank.new('工').between?(Rank.new('士'), Rank.new('商'))  # => true

おしまい。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What are the problem?