class String

truncate extends String to shorten text by character length or number of words.

Public Instance Methods

truncate(length = 20, omis = "...") click to toggle source

The main “truncate” class can be passed a length (in number of characters) and / or a custom omission. The default length is 20 characters and the default omission is “…”.

# File lib/truncate.rb, line 12
def truncate(length = 20, omis = "...")
  text = self.dup
  if text.length > length
    text = text[0...length].strip + omis
  end
  text
end
words(length = 5, omis = "...") click to toggle source

The “words” method can be passed a length (in number of words, splitting on “ ”) and / or a custom omission. The default length is 5 words and the default omission is “…”.

# File lib/truncate.rb, line 25
def words(length = 5, omis = "...")
  text = self.dup
  array = text.split(" ")
  if array.length > length
    text = array[0...length].join(" ") + omis
  end
  text
end