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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With