Topic: Truncating words instead of characters

I suppose the title pretty much speaks for itself. Is there any alternative for the standard truncate(text,20) ? I am trying to make automatic exceprts for my articles...

Re: Truncating words instead of characters

Hmmm.. This isn't exactly the cleanest way to do it, but it's all I could think of.

words = text.split(' ')

count = 0
finished_text = String.new
while count < 20
    finished_text = finished_text + " " + words[count]
    count += 1
end
finished_text = finished_text + "..."

Re: Truncating words instead of characters

Another cleaner way: (I'm learning too tongue)

words = text.split(' ')
finished_text = String.new
1.upto(20) { |c| finished_text += " " + words[c] }
finished_text += "..."
# finished_text is the truncated text, suffixed by "..."

Re: Truncating words instead of characters

Thanks for that, I was able to refactor it to accept length arguments:

[code=ruby]def excerpt(text, length = 30, end_string = '

Re: Truncating words instead of characters

No problem, glad I could contribute cause everyone here is so helpful to me smile