【问题标题】:Want to show the first 50 or 60 words of a text field in ruby?想要在 ruby​​ 中显示文本字段的前 50 或 60 个单词?
【发布时间】:2010-10-17 09:10:14
【问题描述】:

我有一个故事文本字段,并想在快照页面中显示前几行(比如该字段的前 50 个单词)。我如何在 Ruby(在 Rails 上)中做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    假设您的单词由空格分隔,您可以执行以下操作。

    stories.split(' ').slice(0,50).join(' ')
    

    【讨论】:

      【解决方案2】:

      Aaron Hinni's answer基本相同,但会尽量保留3个完整的句子(如果句子太长,则截断至50个字)

      def truncate(text, max_sentences = 3, max_words = 50)
        # Take first 3 setences (blah. blah. blah)
        three_sentences = text.split('. ').slice(0, max_sentences).join('. ')
        # Take first 50 words of the above
        shortened = three_sentences.split(' ').slice(0, max_words).join(' ')
        return shortened # bah, explicit return is evil
      end
      

      另外,如果此文本有任何 HTML,我在 "Truncate Markdown?" 上的回答可能有用

      【讨论】:

        【解决方案3】:

        在 Rails 应用程序中使用非常相似的东西来扩展(“猴子补丁”)基本 String 类。

        我创建了lib/core_extensions.rb,其中包含:

        class String
          def to_blurb(word_count = 30)
            self.split(" ").slice(0, word_count).join(" ")
          end
        end
        

        然后我创建了config/initializers/load_extensions.rb,其中包含:

        require 'core_extensions'
        

        现在我在 Rails 应用程序中的所有 String 对象上都有 to_blurb() 方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-17
          • 2014-11-21
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          • 2011-02-09
          • 1970-01-01
          • 2012-05-25
          相关资源
          最近更新 更多