//DEVGURU

Michał Bielawski @ December 15th, 2009

Truncate string preserving only full words (Ruby, RoR)

Easy method to cut string to a defined length without leaving words cut in half.

class String
  def truncate_full_words limit = 64, completion = "..."
    self.length > limit ? "#{self[0..(self.rindex(' ', limit) || limit)-1]}#{competion}" : self
  end
  def truncate_full_words! limit = 64, completion = "..."
    self.replace(self.truncate_full_words limit, completion)
  end
end

Usage:

>> some_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec enim nibh."
=> "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec enim nibh."
>> some_string.truncate_full_words
=> "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ..."

Have fun using it :)

Comment this post!