Search code examples
rubyruby-on-rails-3jrubysubstringwords

Get first N characters from string without cutting the whole words


I want to know if there an easy way to get only N symbols from string without cutting the whole words.

For example, I have products and products descriptions information. The description length is from 70 to 500 symbols, but I want to display only the first 70 symbols like this:

Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world.

On May 8, 2011, Coca-Cola celebrated its 125thanniversary. Created in 1886 in Atlanta, Georgia, by Dr. John S. Pemberton, Coca-Cola was first offered as a fountain beverage at Jacob's Pharmacy by mixing Coca-Cola syrup with carbonated water.

So, ordinary sub string method will give me:

Coca-Cola is the most popular and biggest-selling soft drink in histor

and I need a method to get only this:

Coca-Cola is the most popular and biggest-selling soft drink in ...

Solution

  • s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."
    s = s.split(" ").each_with_object("") {|x,ob| break ob unless (ob.length + " ".length + x.length <= 70);ob << (" " + x)}.strip
    #=> "Coca-Cola is the most popular and biggest-selling soft drink in"