核心擴充套件字串過濾器

字串#擠

返回給定字串的版本,不帶前導或尾隨空格,並將內部的所有連續空格組合為單個空格。破壞性版本 squish! 直接在字串例項上執行。

處理 ASCII 和 Unicode 空白。

%{ Multi-line
   string }.squish                   # => "Multi-line string"
" foo   bar    
       boo".squish # => "foo bar boo"

字串#刪除

返回一個新字串,其中刪除了所有出現的模式。破壞性版本 remove! 直接在給定的字串上執行。

str = "foo bar test"
str.remove(" test")                 # => "foo bar"
str.remove(" test", /bar/)          # => "foo "

字串#截斷

如果字串長度超過長度,則返回以給定長度截斷的給定字串的副本。

'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

傳遞一個字串或正規表示式:separator 在自然休息時截斷

'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# => "Once upon a time in a..."

'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# => "Once upon a time in a..."

字串#truncate_words

返回在給定數量的單詞後截斷的字串。

'Once upon a time in a world far far away'.truncate_words(4)
# => "Once upon a time..."

傳遞字串或正規表示式以指定不同的單詞分隔符

'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>')
# => "Once<br>upon<br>a<br>time<br>in..."

最後一個字元將替換為:omission 字串(預設為“…”)

'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
# => "And they found that many... (continued)"

字串#strip_heredoc

剝離 heredocs 中的縮排。查詢最少縮排的非空行並刪除前導空格的數量。

if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end

使用者會看到

This command does such and such.

Supported options are:
-h         This message
...