0

Given an array, say %w[ a b c a a b b c c c]. The method should return 3, as it is the maximum quantity of adjacent duplicates ( 3 'c' )

This is what I came up with so far:

def check_quantity_of_same_adjacent_elements(array)
  max = 0
  array.each_index do |i|
    max += 1 if array[i] == array[i+1]
  end
  max
end

but it obviously don't work as it returns the number of all duplicates

2
  • Why would you want to do this? Is this a homework question? (There's a homework tag if so) Commented Aug 28, 2014 at 14:42
  • No, it's not a homework, it's an actual task I have to accomplish in order to create slot machine in ruby Commented Aug 28, 2014 at 14:44

1 Answer 1

2
%w[a b c a a b b c c c].chunk{|e| e}.map{|_, v| v.length}.max #=> 3
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain me what purpose does the underscore there serve? I only can find map.with_index which takes two parameters
_ is known as a "black-hole" variable. It's used to assign values to, but never retrieve them, and is useful when you know something is going to be passed but want to ignore it.
This is just a community coding convention, but it has been so widely adopted that even the Ruby implementations were modified to nut generate an "unused parameter" or "unused local variable" warning for identifiers starting with an underscore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.