コンテンツにスキップ

オブジェクト

オブジェクトの比較

同一性の比較

  • Object#equal? : 同一オブジェクトの場合に true を返す。
  • Object#eql? : 同値の場合に true を返す。
a1 = "abc"
a2 = 'abc'

print a1.equal? a2    # => false
print a1.eql? a2      # => true

大小関係の比較

クラスを定義する際に、<=>(other) メソッドを定義しておくと、オブジェクトの大小関係を比較できる。

class Person
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def <=>(other)
    self.age <=> other.age
  end
end

person1 = Person.new("Alice", 30)
person2 = Person.new("Bob", 25)

# 年齢で比較
puts person1 > person2  # => true
puts person1 < person2  # => false

# 配列を年齢でソート
people = [person2, person1]
people.sort!  # => [#<Person:0x00007f8a18b69610 @name="Bob", @age=25>, #<Person:0x00007f8a18b694b0 @name="Alice", @age=30>]