ruby - 实例方法 "each_with_index"在哪里定义的?

标签 ruby enumerable

我正在寻找 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.superclasssObjectObject没有实现这个实例方法。

最佳答案

它来自 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/

相关文章:

ruby-on-rails - 在 Rails 站点上显示 Twitter 提要(具有历史记录)的最佳方式

ruby - 平整输出中的打印符号

ruby - rails3.1 自动加载失败

ruby - 如何在数据库中存储 ruport 表数据对象?

javascript - 为什么可枚举: false not cascade to inherited classes in TypeScript?

arrays - 如何根据每个元素的特征对 ruby​​ 数组中的项目进行分组?

ruby-on-rails - 如何在 erb 中使用带有枚举的 block

ruby - Rails 3.2.3 + Twitter Bootstrap + Nav-Tabs : How to show a specific tab?

Ruby 删除可枚举列表中的重复项

ruby - 参数错误 : comparison of NilClass with 1 failed min_by