I am also not a very Ruby person, but as I noted in another comment, this seems to work for the described algorithm.
s = "mississippi" s.split('').sort.join.gsub(/(.)\1{2,}/) { |s| s.length.to_s + s[0,1] }
Of course, you need to make sure that the word has lowercase letters, does not contain numbers, etc.
As requested, I will try to explain the code. Please forgive me if I do not get all the correct terminology of Ruby or reg ex, but here.
I think the split / sort / join section is pretty simple. The interesting part for me begins when gsub is called. This will replace the substring that matches the regular expression with the return value from the subsequent block. Reg ex finds any character and creates a back link. This is the "(.)" Part. Then we continue the matching process using the "\ 1" backlink, which evaluates any character found in the first part of the match. We want this character to be found at least two more times for the total minimum number of occurrences of three. This is done using the quantifier "{2,}".
If a match is found, the corresponding substring is then passed to the next block of code as an argument thanks to "| s |" part. Finally, we use the string equivalent of the corresponding substring length and add to it any character that makes up this substring (they should all be the same) and return the concatenated value. The return value replaces the original substring. The whole process continues until nothing is found, because it is a global replacement for the original string.
I apologize if this is embarrassing. As often happens, it’s easier for me to visualize the solution than to clearly explain it.
Robert Simmons
source share