13
<%= 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 (...)

user664833
  • 16,967
  • 18
  • 88
  • 129
user852974
  • 2,202
  • 10
  • 39
  • 64

4 Answers4

24

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..."
user664833
  • 16,967
  • 18
  • 88
  • 129
Radhika
  • 2,253
  • 1
  • 19
  • 27
16

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
  end
end
text = "aa bb cc dd ee ff"
p text.words_limit(3)
# => aa bb cc...
gilsilas
  • 1,411
  • 2
  • 14
  • 24
11

Try the following:

'this is a line of some words'.split[0..3].join(' ')
=> "this is a line" 
user664833
  • 16,967
  • 18
  • 88
  • 129
ndrix
  • 1,051
  • 11
  • 17
2
   # Message helper
   def content_excerpt(c)
     return unlessc
     c.split(" ")[0..4].join + "..."
   end

   # View
   <%= message.content_excerpt %>

But the common way is truncate method

   # Message helper
   def content_excerpt(c)
     return unless c
     truncate(c, :length => 20)
   end
Anatoly
  • 14,870
  • 4
  • 49
  • 75