diary

I like Hatena Star with a text selection.

2020-07-19

github.com

rbsを速くした。


module M
  def self.extended(mod)
    mod.class_eval do
      @@objects = ObjectSpace::WeakMap.new

      def self.new(*args)
        @@objects[args.hash] ||= super
      end

      class << self
        ruby2_keywords :new
      end
    end
  end
end

class C
  extend M

  def initialize(x:)
    @x = x
  end
end


c1 = C.new(x: 1)
c2 = C.new(x: 1)
c3 = C.new(x: 2)

p c1, c2, c3
p c1.equal? c2 # => true
p c1.equal? c3 # => false

同じ引数で初期化された時には同じオブジェクトを返すnew

ただし、#hashが衝突したときのことを考えていない。 ObjectSpace::WeakMapはどうやらキーの一致判定にequal?を使っていそう