hey mike hey mike - 4 months ago 30
Ruby Question

how to compare to previous item in `each` iterator?

update: sorry, I fixed my program:

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


Is there another beautiful way in
ruby
language to do the same thing ?

btw, actually.
a
is a
ActiveRecord::Relation
in my real case.

Thanks.

Answer

The problem you might have with each_cons is that it iterates through n-1 pairs (if the length of the Enumerable is n). In some cases this means you have to separately handle edge cases for the first (or last) element.

In that case, it's really easy to implement a method similar to each_cons, but which would yield (nil, elem0) for the first element (as opposed to each_cons, which yields (elem0, elem1):

module Enumerable
  def each_with_previous
    self.inject(nil){|prev, curr| yield prev, curr; curr}
    self
  end
end
Comments