I'm creating a function that takes a string and creates an acronym but am running into errors.
When I input "Complementary metal-oxide semiconductor" I get "CS" in return when expecting "CMOS". Any suggestions why this might happen? I pass it plenty of other strings and it works, just doesn't work in this case.
class Acronym
def self.abbreviate(phrase)
letters = phrase.split("")
acronym = []
letters.each do |letter|
previous = letters.index(letter) - 1
if previous == -1
acronym.push(letter)
elsif letters[previous] == " " || letters[previous] == "-"
acronym.push(letter)
end
end
acronym.join("").upcase
end
end
The issue with your code is that
index()returns the first occurrence of the given letter. So, two problems:push().CSCCbecause there are two 'c's in 'semiconductor'.As an alternative, here is an option that uses regex:
Step by step:
.gsubfrom @DollarChills to turn the '-' into a space.scan()returns an array of all matches. The regex matches the first word in the string and any word that is preceded by a space.scanis actually an array of arrays, so flatten unnests them.