2016-11-22 39 views
0

我想將字符串中的所有單詞(字母)轉換爲它們的縮寫,如i18n。換句話說,我想將"extraordinary"更改爲「e11y」,因爲"extraordinary"的第一個和最後一個字母之間有11個字符。它適用於字符串中的單個單詞。但是我怎樣才能對多字串做同樣的事情呢?當然,如果一個單詞是<= 4,沒有必要從它縮寫。陷入縮寫實現ruby字符串

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.")) 

回答

1
def short_form(str) 
    str.gsub(/[[:alpha:]]{4,}/) { |s| "%s%d%s" % [s[0], s.size-2, s[-1]] } 
end 

正則表達式寫道:「比賽四個或更多的字母字符」。

short_form "abc"   # => "abc" 
short_form "a-b-c"  #=> "a-b-c" 
short_form "cats"   #=> "c2s" 
short_form "two-ponies-c" #=> "two-p4s-c" 
short_form "Humpty-Dumpty, who sat on a wall, fell over" 
    #=> "H4y-D4y, who sat on a w2l, f2l o2r" 
+0

感謝@KirillZhuravlov標記我犯的一個錯誤。 –

+1

我最初認爲轉換隻適用於單詞或帶連字符的單詞。我修改了我的答案來處理字符串。 –

5

你的錯誤是你的第二個參數是x(原整個字符串)工作作爲一個整體替換字符串。

代替使用的gsub形式,其中第二個參數是替換字符串的,使用的gsub形式,其中第二個參數是(上市,例如,第三上this page)。現在您正在將的每個子字符串接收到您的塊中,並且可以單獨使用那個子串。

+0

它讓我考慮到了,謝謝。 –

1

我會建議沿東西這行:

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 
+0

測試通過,謝謝! –

1

接受的答案是不壞,但它可以通過不匹配是在第一時間太短的話進行簡單得多:

def abbreviate(str) 
    str.gsub(/([[:alpha:]])([[:alpha:]]{3,})([[:alpha:]])/i) { "#{$1}#{$2.size}#{$3}" } 
end 

abbreviate("You, and I, should speak.") 
# => "You, and I, s4d s3k." 

或者,我們可以回顧後使用, lookahead,這使得正則表達式更復雜,但替換更簡單:

def abbreviate(str) 
    str.gsub(/(?<=[[:alpha:]])[[:alpha:]]{3,}(?=[[:alpha:]])/i, &:size) 
end 
+0

我相信這個答案更完整 –

+1

問題不明確哪些字符可以在轉換的字符串中。它們可能是字母字符,字母數字字符或所有字符,但我懷疑它們是否是「字符字符」('\ w'),考慮到「」______「str.gsub(/(\ w)(\ w { 3,})(\ w)/){「#{$ 1}#{$ 2.size}#{$ 3}」}#=>「_5_」'。如果''_5_「'確定,那麼爲什麼不''」-5「'? –

+0

@CarySwoveland OP在他們自己的代碼中使用了'\ w',所以我做了演繹性的飛躍。 –