我有一个脚本迭代使用ObjectSpace#each_object没有args.然后它打印每个类存在多少个实例.
我意识到有些类重新定义了#class实例方法,所以我必须找到另一种方法来获得实际的类; 假设它存储在变量中"klass",并且klass === object是真的.
在Ruby 1.8中我可以做到这一点,假设Object没有monkeypatched:
Object.instance_method(:class).bind(object).call
Run Code Online (Sandbox Code Playgroud)
这适用于以下ActiveSupport::Duration情况:
# Ruby 1.8
# (tries to trick us)
20.seconds.class
=> Fixnum
# don't try to trick us, we can tell
Object.instance_method(:class).bind(20.seconds).call
=> ActiveSupport::Duration
Run Code Online (Sandbox Code Playgroud)
但是,在Ruby 1.9中,这不再起作用:
# Ruby 1.9
# we are not smart...
Object.instance_method(:class).bind(20.seconds).call
TypeError: bind argument must be an instance of Object
from (irb):53:in `bind'
from (irb):53
from /Users/user/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
Run Code Online (Sandbox Code Playgroud)
事实证明,这是ActiveSupport::Duration子类ActiveSupport::BasicObject.后者::BasicObject在Ruby 1.9中是子类,因此 …