0

下午所有,

我有一个名为 content 的字段,它是 Snippet 的字符串。Snippet 是 Book 的孩子。我想获得每个片段中所有内容的总字数,以定义总字数,然后我可以限制它以进行验证。

任何人都知道如何做到这一点,或者给我一个内部网络其他地方所需的代码示例。

对此进行快速扩展。我需要为书本模型中当前存储为 [0,1,2] 的书本模型中的 :size 下的每种尺寸定义不同的字数。我该怎么做?

4

2 回答 2

2

我不太明白你问题的第一部分的意思,但如果你想用 Ruby 在字符串中找到字数,你可以这样做:

str.scan(/\w+/).size
于 2013-10-20T19:14:51.097 回答
0

您可以使用 'each - do' 遍历 Book 中的所有 Snippets:

class Book < ActiveRecord::Base
  has_many :snippets

  ...

  def get_word_count
    @word_count = 0
    self.snippets.each.do |c|
      @word_count += c.content.scan(/\w+/).size
    end
  end
end

class Snippets < ActiveRecord::Base
  belongs_to :book
  ...
end

扩展问题的 UPD

您可以通过 word_counts 数组设置不同的 word_count 函数,然后使用:size

def get_word_count
  #special word_counts for different sizes
  wc_func = [];
  wc_func[0] = { |cont| cont.length } # for size 0
  wc_func[1] = { |cont| cont.scan(/\w+/).size } # for size 1

  #word count
  @word_count = 0
  self.snippets.each.do |c|
    @word_count += wc_func[@size][c.content]
  end
end

或遍历案例:

def get_word_count
  case @size
  when 0
    wc_func = { |cont| cont.length } # for size 0
  when 1
    wc_func = { |cont| cont.scan(/\w+/).size } # for size 1
  else
    wc_func = { |cont| cont.length/2 + 5 } # for other sizes
  end

  #word count
  @word_count = 0
  self.snippets.each.do |c|
    @word_count += wc_func[c.content]
  end
end
于 2013-10-20T19:31:02.423 回答