我正在寻找 Ruby 1.8.6 docs ,并且那里没有提到 each_with_index
。
但是,如果我启动 Ruby 1.8.7 或 1.9.2 并运行以下命令,它会起作用:
h = {:a => 1, :b => 2.2}
h.each_with_index do |pair, i|
p pair, i
end
each_with_index
从何而来? Hash.superclasss
是Object
,Object
没有实现这个实例方法。
最佳答案
它来自 Enumerable,一个混入 Hash 的模块。
执行 Hash.ancestors
以查找对 Enumerable 的提及。
Hash.ancestors => [Hash, Enumerable, Object, Kernel, BasicObject]
Enumerable.instance_methods.grep(/each/) # => [:each_with_index, :reverse_each, :each_slice, :each_cons, :each_with_object]
关于ruby - 实例方法 "each_with_index"在哪里定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103939/