Kirill Zhuravlov Kirill Zhuravlov - 10 days ago 6
Ruby Question

Stuck in Abbreviation implementation to ruby string

I want to convert all the words in the string to their abbreviations like i18n does. In other words I want to change

"extraordinary"
into "e11y" because there are 11 characters between the first and the last letter in
"extraordinary"
. It works with a single word in the string. But how can I do the same for a multi-word string? And of course if a word is
<= 4
there is no point to make an abbreviation from it.

class Abbreviator

def self.abbreviate(x)
x.gsub(/\w+/, "#{x[0]}#{(x.length-2)}#{x[-1]}")
end

end

Test.assert_equals( Abbreviator.abbreviate("banana"), "b4a", Abbreviator.abbreviate("banana") )
Test.assert_equals( Abbreviator.abbreviate("double-barrel"), "d4e-b4l", Abbreviator.abbreviate("double-barrel") )
Test.assert_equals( Abbreviator.abbreviate("You, and I, should speak."), "You, and I, s4d s3k.", Abbreviator.abbreviate("You, and I, should speak.") )

Answer

I would recommend something along the lines of this:

class Abbreviator
  def self.abbreviate(x)
    x.gsub(/\w+/) do |word|
      # Skip the word unless it's long enough
      next word unless word.length > 4
      # Do the same I18n conversion you do before
      "#{word[0]}#{(word.length-2)}#{word[-1]}"
    end
  end
end
Comments