If I have some text
that I want to print out on a page, but only want to print say the first 100 words before eclipsing it... what's the easiest way to do this?
views:
175answers:
3How's this for a start:
def first_words(s, n)
a = s.split(/\s/) # or /[ ]+/ to only split on spaces
a[0...n].join(' ') + (a.size > n ? '...' : '')
end
s = "The quick brown fox jumps over the lazy dog. " * 20
puts "#{s.size}, #{s.split(/\s/).size}"
#-> 900, 180
puts first_words(s, 10)
#-> The quick brown fox jumps over the lazy dog. The...
puts first_words("a b c d", 10)
#-> a b c d
You have a couple of options, one way is that you could say that a word is n characters and then take a substring of that length, append the ellipsis to the end and display it. Or you could run though the string and count the number of spaces, if you assume that there is only one space between each of the words, then the 100th space will be after then 100th word, append the ellipsis and you are done.
Which one has better performance would likely depend upon how the functions are written, most likely the substring operation is going to be faster than counting the spaces. However, the performance difference might be negligible so unless you are doing this a lot, counting spaces would likely be the most accurate way to go.
Also, just as a reference, the average length of a word in the English language is 5.1 characters.