DEV Community

Discussion on: Daily Challenge #180 - SMS Shortener

Collapse
 
cipharius profile image
Valts Liepiņš

This one ended up being less readable, will give a compact version and expanded version with commentary. Once again, Ruby:

def shortenSMS str
    [str.length - 160, str.count(' ')].min.times do
        str.sub!(/\s(\S*)$/) { $1[0].upcase + $1[1..] }
    end
    str[0...160]
end

Explained version:

def shortenSMS str
    # Get basic message statistics
    excessChars = str.length - 160
    spacesCount = str.count(' ')
    # How many substitutions should be done
    subCount = [excessChars, spacesCount].min

    subCount.times do
        # Substitutes with mutation first space from end, capturing the tail
        str.sub!(/\s(\S*)$/) do
            # Upcase first character of tail and append rest
            # $1.capitalize won't do, because it lowercases rest of the string
            $1[0].upcase + $1[1..]
        end
    end
    # Ensure that message is 160 chars long
    str[0...160]
end