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/