1

我正在查看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_indexHash.superclasssObject,并且Object没有实现这个实例方法。

4

3 回答 3

6

它来自 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]
于 2011-05-23T23:00:37.450 回答
2

它来自Enumerable模块,请参见此处。这背后的概念称为此处此处mixins详细解释。

于 2011-05-23T23:02:10.410 回答
1

模块可枚举

于 2011-05-23T23:01:19.290 回答