Kirill Zhuravlov Kirill Zhuravlov - 16 days ago 6
Ruby Question

How to find the number of times in which the symbol is duplicated in a string Ruby

How to find the number of times in which the symbol is duplicated in a string?

def duplicate_count(text)
t = text.downcase
t...
end

Test.assert_equals(duplicate_count("abc"), 0)
Test.assert_equals(duplicate_count("abcdeaa"), 1)
Test.assert_equals(duplicate_count("abcdeaB"), 2)

Answer

One way, it ain't pretty but works:

def duplicates string
  string.downcase.split('')
                 .group_by { |i| i }
                 .to_a
                 .select { |i| i[1].size > 1 }
                 .size
end

duplicates "abc"     #=> 0
duplicates "abcdeaa" #=> 1
duplicates "abcdeaB" #=> 2

A slightly better implementation:

def duplicates string
  string.downcase.split('')
                 .group_by { |i| i }
                 .values
                 .select { |i| i.size > 1 }
                 .size
end