更新:對不起,我固定我的程序:如何比較`each`迭代器中的前一項?
a = [ 'str1' , 'str2', 'str2', 'str3' ]
name = ''
a.each_with_index do |x, i |
if x == name
puts "#{x} found duplicate."
else
puts x
name = x if i!= 0
end
end
output:
str1
str2
str2 found duplicate.
str3
是否有ruby
語言的另一個美麗的方式做同樣的事情?
btw,實際上。在我的真實情況下,a
是ActiveRecord::Relation
。
謝謝。
嘗試用詞語解釋意圖,代碼看起來有問題(尤其是'x [i-1]'沒有意義)。最好的方法是:給出一些輸入和預期輸出的例子。 – tokland 2012-03-01 13:39:17
謝謝,我修復了我的程序。 – 2012-03-01 14:14:13
each_cons仍然適合嗎? – 2012-03-01 14:14:30