Shaun Frost Duke Jackson
Shaun Frost Duke Jackson

Reputation: 1266

Counting words in strings

Afternoon All,

I have a field called content which is the string for Snippet. Snippet is the child of Book. I would like to get a total word count of all content in every snippet in order to define a total word count and then I can limit it against a validation.

Anyone have any ideas how to do this or give me an example of the code needed from elsewhere on the innerweb.

Quick one on extension to this. I need to define a different word count for every size in book currently stored as [0,1,2] under :size in the book model. How would I do this?

Upvotes: 0

Views: 1101

Answers (2)

Leger
Leger

Reputation: 1184

You can iterate over all Snippets in a Book with 'each - do':

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 for extension question

You can set different word_count functions via array of word_counts and then index 'em with :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

OR run through cases:

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

Upvotes: 0

Tri-Edge AI
Tri-Edge AI

Reputation: 340

I didn't quite get what you mean with the first part of your question, but if you wanna find the word count in a string with Ruby you can do something like this:

str.scan(/\w+/).size

Upvotes: 2

Related Questions