ruby - 迭代时返回迭代对象和索引

标签 ruby

array = [1,2,3,{:name => "Peter"}, "hello"]
array.each do |element| # it can be "inject", "map" or other iterators
  # How to return object "array" and position of "element"
  # also next and priviouse "element"
end

当然我可以通过 array.index[element] 返回索引,但我正在寻找更自然的解决方案。就像 Rails 关联中的 proxy_owner

ruby 1.8.7

我要输出什么?我想返回我迭代的对象(在我的例子中是数组),还有迭代次数(在 each_with_index 的情况下是索引)下一个和迭代的 priviouse 元素。

作为输入,我有一个数组和迭代器(每个、映射、注入(inject)等)

最佳答案

使用Enumerable#each_cons。以下是来自 ruby1.8.7 rdoc 的副本.它应该适用于 ruby​​ 1.8.7。


  • 每个缺点(n){...}
  • 每个缺点(n)

为每个连续元素数组迭代给定 block 。如果没有给出 block ,则返回一个枚举器。


有了这个,你可以给出一个数组:

['a', 'b', 'c', 'd', 'e'].each_cons(3).to_a

# => ["a", "b", "c"], ["b", "c", "d"], ["c", "d", "e"]]

或者做:

['a', 'b', 'c', 'd', 'e'].each_cons(3) {|previous, current, nekst|
    puts "#{previous} - #{current} - #{nekst}"
}

# => a - b - c
# => b - c - d
# => c - d - e

如果你想要索引,

['a', 'b', 'c', 'd', 'e'].each_cons(3).to_a.each_with_index {|(previous, current, nekst), i|
    puts "#{i + 1}. #{previous} - #{current} - #{nekst}"
}

# => 1. a - b - c
# => 2. b - c - d
# => 3. c - d - e

您可以非常普遍地将数组传递给其他枚举器,例如,使用 inject:

['a', 'b', 'c', 'd', 'e'].each_cons(3).to_a.inject(''){|str, (previous, current, nekst)|
    str << previous+current+nekst
}

# => "abcbcdcde"

关于ruby - 迭代时返回迭代对象和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5444898/

相关文章:

ruby - 点列表的 RGeo 凸包

ruby - 如何列出包括点文件但不包括 .和 ..?

ruby-on-rails - 获取当前季度的月数

ruby - 如何在 Ruby 中的 RestClient gem 中设置超时?

Ruby 获取句子中最长的单词

javascript - 计算 JavaScript/NodeJS/Underscore 中的哈希值

ruby-on-rails - 在 Ruby ActiveRecord 中处理列转换

ruby-on-rails - 为什么这在 IRB 中有效而无效?

css - 是否可以使用 Twitter Bootstrap 或 CSS 选择器淡出 Devise 警报?

ruby - 使用Logstash Ruby过滤器解析csv文件