オブジェクト
オブジェクトの比較
同一性の比較
Object#equal?
: 同一オブジェクトの場合にtrue
を返す。Object#eql?
: 同値の場合に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>]