Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Ruby | Object | __id__ or object_id

概要

Object#__id__ or object_id -> Integer

詳細

オブジェクトのハッシュ値を返却。
Hashクラスで利用。

サンプルコード
require 'set'

a = "hoge"
b = "hoge"

# String は eql? が同値チェックになっている
p a == b # => true
p a.eql? b # => true
p a.equal? b # => false

a = :hoge
b = :hoge

# Symbol は eql? が同値チェックになっていて、
# singleton のため object_id も同じになっている
p a == b # => true
p a.eql? b # => true
p a.equal? b # => true

class Person
  attr_reader :name, :age

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

  def ==(other)
    @name == other.name && @age == other.age
  end
end

a = Person.new('tanaka', 25)
b = Person.new('tanaka', 25)

# 自作クラスはデフォルトだと eql? と equal? が同じ挙動
p a == b # => true
p a.eql? b # => false
p a.equal? b # => false
p a.hash # => -776684713
p b.hash # => 255701755
p a.object_id # => 20693676
p a.__id__ # => 20693676
p b.object_id # => 20071296
p b.__id__ # => 20071296
print Set[a, b].size, "\n" # => 2
print [a, b].uniq.size, "\n" # => 2
people_hash = {}
people_hash[a] = 1
people_hash[b] = 2
print people_hash.size, "\n" # => 2

class Person
  def eql?(other)
    @name == other.name && @age == other.age
  end

  def hash
    [@name, @age].hash
  end
end

# 自作クラスの eql?, hash をオーバーライドすると同値チェックを実現できる
p a == b # => true
p a.eql? b # => true
p a.equal? b # => false
p a.hash # => -535996792
p b.hash # => -535996792
p a.object_id # => 20857380
p a.__id__ # => 20857380
p b.object_id # => 20661000
p b.__id__ # => 20661000
print Set[a, b].size, "\n" # => 1
print [a, b].uniq.size, "\n" # => 1
people_hash = {}
people_hash[a] = 1
people_hash[b] = 2
print people_hash.size, "\n" # => 1