Get first N characters from string without cutting the whole words

gotqn picture gotqn · May 6, 2013 · Viewed 10.2k times · Source

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

Answer

ivanxuu picture ivanxuu · Jan 27, 2015

Just use truncate with separator option:

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

Get more info at: truncate helper in rails API documentation