[Solved] Counting changes in an array


Below one is solution I believe. Sure there is more room to refactor it, you can start from here.

a = ["red", "orange", "green", "red", "yellow", "blue", "green"]    
a.reject {|e| !['red', 'green'].include? e }
  .each_cons(2)
  .select{|e| e == ['red', 'green']}
  .size

A more artistic version.

def neither_red_nor_green e
  !['red', 'green'].include? e
end

def red_followed_by_green ary
  ary == ['red', 'green']
end

a.reject(&method(:neither_red_nor_green))
  .each_cons(2)
  .select(&method(:red_followed_by_green))
  .size

UPDATE

Thanks to @Stefan for below suggestions.

def either_red_or_green e
  ['red', 'green'].include? e
end

def red_followed_by_green ary
  ary == ['red', 'green']
end


a.select(&method(:either_red_or_green))
  .each_cons(2)
  .count(&method(:red_followed_by_green))

UPDATE

As Stefan Pochmann proposed,

a.select(&method(:either_red_or_green))
  .each_cons(2)
  .count(['red', 'green'])

will do the same work, without needing another method call.

9

solved Counting changes in an array