Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 808
hey mike Avatar asked Mar 01 '12 13:03

hey mike


2 Answers

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
like image 128
Mladen Jablanović Avatar answered Oct 05 '22 22:10

Mladen Jablanović


you can use each_cons:

irb(main):014:0> [1,2,3,4,5].each_cons(2) {|a,b| p "#{a} = #{b}"}
"1 = 2"
"2 = 3"
"3 = 4"
"4 = 5"
like image 23
Vasiliy Ermolovich Avatar answered Oct 05 '22 21:10

Vasiliy Ermolovich