Displaying Only the first x words of a string in rails

前端 未结 4 840
眼角桃花
眼角桃花 2020-12-31 08:47
<%= 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 st

4条回答
  •  不知归路
    2020-12-31 09:09

    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...
    

提交回复
热议问题