【问题标题】:Is it possible to check to the position of an iterator in Ruby? [duplicate]是否可以检查 Ruby 中迭代器的位置? [复制]
【发布时间】:2012-06-22 12:56:58
【问题描述】:

有没有办法获取迭代器的位置(迭代了多少次)?

values = (1..100)
values.each do |value|
  if ... % 10 == 1 then puts iterator.count end
end

或者你必须明确计算:

values = (1..100)
counter = 0
values.each do |value|
  if counter % 10 == 1 then puts counter end
  counter += 1
end

有更清洁的方法吗?

Ruby 1.9.2

【问题讨论】:

    标签: ruby foreach iterator ruby-1.9.2


    【解决方案1】:

    使用each_with_index

    values.each_with_index do |value, idx|
      puts idx if idx % 10 == 1
      # do something else
    end
    

    或者你可以使用更酷的替代品

    values.each.with_index do |value, idx|
      # work
    end
    

    我称它为cooler,因为#with_index 的知名度相对较低,它可以与map(和其他方法)结合使用以产生有趣的结果。

    【讨论】:

    • .with_index 也适用于哈希:hash.each_key.with_index |key, idx|
    • @BSeven:此外,它适用于任何返回枚举数的方法:)
    • 两个(次要)注意事项:1)each_with_index 也可以与map 一起使用(Ruby >= 1.8.7)。 2) values.each.with_index 的行为实际上与 values.map.with_index 相同。
    • @tokland:谢谢!不知何故,我从来没有尝试过使用mapeach_with_index :)
    猜你喜欢
    • 2017-02-23
    • 1970-01-01
    • 2017-04-05
    • 2021-08-02
    • 1970-01-01
    • 2013-09-23
    • 2023-03-10
    • 1970-01-01
    • 2010-09-30
    相关资源
    最近更新 更多