1
hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
  hash[item] = index
}
hash   #=> {"cat"=>0, "dog"=>1, "wombat"=>2}

来自 RubyDoc 的示例

我必须遍历 100k 个对象的集合。通常我会做一个 find_each 但在这种情况下我也需要索引。我可以制作自己的索引,但我想知道这种情况是否存在红宝石。

我想要像 collection.find_each_with_index 这样的东西

谢谢

4

1 回答 1

0

不是纯 Ruby,但可能对那些来到这里并希望在 Rails 框架内回答这个问题的人有所帮助。

https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/Batches.html#method-i-find_each

Person.find_each.with_index do |person, index|
  person.award_trophy(index + 1)
end
于 2021-02-13T03:03:34.070 回答