Hi,

Really need a little help understanding how to implement Enumerable -
maybe I'm thinking about this the wrong way - what I'd like to do is:

sm = ScoreMatrix.new
sm.keywords << Keyword.new(1)
sm.keywords << Keyword.new(2)
sm.keywords.sum #=> returns 3

I currently have:

class ScoreMatrix
  def initialize
    @keywords = [] # <= what do I put here?
  end

  def keywords
    @keywords
  end
end

class Keyword
  include Enumerable

  attr_accessor :hits

  def initialize(hits)
    @hits = hits
    @array = []
  end

  def sum
    total = 0
    @array.each do |item|
      total += item.hits
    end
    total
  end

  def each
    @array.each do |item|
      yield item
    end
    self
  end

  def add(item)
    @array.push(item)
    self
  end
  alias :<< :add
end

Am I on the right track or way off? :0)

Many Thanks

Luke
-- 
Posted via http://www.ruby-forum.com/.