How to compare with the previous paragraph 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 great way in ruby to do the same?

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

Thanks.

+7
source share
5 answers

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

In this case, it is very easy to implement a method similar to each_cons , but which will give (nil, elem0) for the first element (unlike each_cons , which gives (elem0, elem1) :

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

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" 
+12
source

You can use each_cons

 a.each_cons(2) do |first,last| if last == name puts 'got you!' else name = first end end 
+5
source

You can use Enumerable # each_cons :

 a = [ 'str1' , 'str2', 'str3' , ..... ] name = '' a.each_cons(2) do |x, y| if y == name puts 'got you! ' else name = x end end 
+3
source

As you probably want to do more than puts with duplicates, I would rather keep duplicates in the structure:

  ### question example: a = [ 'str1' , 'str2', 'str2', 'str3' ] # => ["str1", "str2", "str2", "str3"] a.each_cons(2).select{|a, b| a == b }.map{|m| m.first} # => ["str2"] ### a more complex example: d = [1, 2, 3, 3, 4, 5, 4, 6, 6] # => [1, 2, 3, 3, 4, 5, 4, 6, 6] d.each_cons(2).select{|a, b| a == b }.map{|m| m.first} # => [3, 6] 

Read more about: https://www.ruby-forum.com/topic/192355 (cool answer by David A. Black)

+1
source

All Articles