Displaying Only the first x words of a string in rails

<%= message.content %>

I can display a message like this, but in some situations I would like to display only the first 5 words of the string and then show an ellipsis (...)


In rails 4.2 you can use truncate_words.

'Once upon a time in a world far far away'.truncate_words(4)
=> "Once upon a time..."

you can use truncate to limit length of string

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

with given space separator it won't cut your words.

If you want exactly 5 words you can do something like this

class String
  def words_limit(limit)
    string_arr = self.split(' ')
    string_arr.count > limit ? "#{string_arr[0..(limit-1)].join(' ')}..." : self
text = "aa bb cc dd ee ff"
p text.words_limit(3)
# => aa bb cc...

Try the following:

'this is a line of some words'.split[0..3].join(' ')
=> "this is a line" 

   # Message helper
   def content_excerpt(c)
     return unlessc
     c.split(" ")[0..4].join + "..."

   # View
   <%= message.content_excerpt %>

But the common way is truncate method

   # Message helper
   def content_excerpt(c)
     return unless c
     truncate(c, :length => 20)

Need Your Help

Debugging of 128 point FFT


I'm implementing 128 point fft using IP CORE. In datasheeet of FFT IP core v-7 DS260 it is mentioned that input must be given in 2's complement form and in fixedpoint representation.Can anyone tel...

Custom JComponent with embedded Swing components not positioned in exported image

java swing jcomponent paintcomponent

I have a funny problem trying to export custom Java JPanels to a PNG file. The export process of the components I've been writing up until now have worked flawlessly.