What\'s the best way to truncate a string to the first n words?
You can use str.split.first(n).join(' ')
with n being any number.
Contiguous white spaces in the original string are replaced with a single white space in the returned string.
For example, try this in irb:
>> a='apple orange pear banana pineaple grapes'
=> "apple orange pear banana pineaple grapes"
>> b=a.split.first(2).join(' ')
=> "apple orange"
This syntax is very clear (as it doesn't use regular expression, array slice by index). If you program in Ruby, you know that clarity is an important stylistic choice.
A shorthand for join
is *
So this syntax str.split.first(n) * ' '
is equivalent and shorter (more idiomatic, less clear for the uninitiated).
You can also use take
instead of first
so the following would do the same thing
a.split.take(2) * ' '