更新:对不起,我固定我的程序:如何比较`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