我正在查看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
没有实现这个实例方法。
我正在查看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]