【问题标题】:Displaying Only the first x words of a string in rails仅显示 rails 中字符串的前 x 个单词
【发布时间】:2011-08-13 07:03:52
【问题描述】:
<%= message.content %>

我可以显示这样的消息,但在某些情况下我想只显示字符串的前 5 个单词,然后显示一个省略号 (...)

【问题讨论】:

标签: ruby-on-rails ruby string


【解决方案1】:

在 rails 4.2 你可以使用truncate_words

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

【讨论】:

    【解决方案2】:

    你可以使用 truncate 来限制字符串的长度

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

    使用给定的空格分隔符不会删减你的话。

    如果你想要正好 5 个单词,你可以这样做

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

    【讨论】:

      【解决方案3】:

      尝试以下方法:

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

      【讨论】:

        【解决方案4】:
           # Message helper
           def content_excerpt(c)
             return unlessc
             c.split(" ")[0..4].join + "..."
           end
        
           # View
           <%= message.content_excerpt %>
        

        但常用的方法是truncate方法

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-19
          • 1970-01-01
          • 2015-08-17
          • 2012-05-09
          • 2012-09-09
          • 2014-10-21
          • 2017-01-13
          • 1970-01-01
          相关资源
          最近更新 更多