From: matz@... Date: 2019-08-29T06:44:04+00:00 Subject: [ruby-core:94650] [Ruby master Feature#16035] Allow non-finalizable objects such as Integer, static Symbol etc in ObjectSpace::WeakMap Issue #16035 has been updated by matz (Yukihiro Matsumoto). I think this is the required behavior for `WeakMap` to implement a cache for example. Accepted. Matz. ---------------------------------------- Feature #16035: Allow non-finalizable objects such as Integer, static Symbol etc in ObjectSpace::WeakMap https://bugs.ruby-lang.org/issues/16035#change-81249 * Author: byroot (Jean Boussier) * Status: Assigned * Priority: Normal * Assignee: nobu (Nobuyoshi Nakada) * Target version: ---------------------------------------- This goes one step farther than what @nobu did in https://bugs.ruby-lang.org/issues/13498 With this patch, special objects such as static symbols, integers, etc can be used as either key or values inside WeakMap. They simply don't have a finalizer defined on them. This is useful if you need to deduplicate value objects, e.g. some minimal use case: ```ruby class Money REGISTRY = ObjectSpace::WeakMap.new private_constant :REGISTRY def self.new(amount) REGISTRY[amount] ||= super.freeze end def initialize(amount) @amount = amount end end if Money.new(42).eql?(Money.new(42)) puts "Same instance" else puts "Different instances" end ``` This is a very simple example, but more complex examples can create use a dynamically created symbol as deduplication key, etc. It also removes one weirdness introduced in the mentioned patch: ```ruby wmap = ObjectSpace::WeakMap.new wmap["foo".to_sym] = Object.new # works fine with dynamic symbols wmap[:bar] = Object.new # cannot define finalizer for Symbol (ArgumentError) ``` Proposed patch: https://github.com/ruby/ruby/pull/2313 -- https://bugs.ruby-lang.org/ Unsubscribe: