baumanj
4/5/2006 6:47:00 PM
James H. wrote:
> Ruby doesn't define the "+=" operator. You need to say this instead:
Sure it does:
$ irb --simple-prompt
>> sum = 0
=> 0
>> sum += 1
=> 1
It's ++ that ruby doesn't define.
> sum = sum + 1
> Or, better yet,
> sum.next
Actually, it would have to be "sum = sum.next" if you actually wanted
to update the value of sum, but there's nothing wrong with sum += 1.
The problem is scope. If you want sum to be an instance variable, you
need to define it as @sum. Also, since you can't reference instance
variables from within the class definition (they must be accessed from
an instance method), you have to declare this in the initialize method
(you could get tricky and do it conditionally in the tag_start method,
but what's the point?). Finally, to give read-only access to this
attribute from outside the class, you can use the attr_accessor macro.
Then you'll be able to access the sum attribute as list.sum. This
version should work:
require "rexml/document"
include REXML
class Listener
attr_accessor :sum
def initialize
@sum = 0
end
def text(text)
puts text
end
def xmldecl(version,encoding,standalone)
puts version
puts encoding
end
def tag_start(name,attrs)
if name == "document"
@sum += 1
end
end
def tag_end(name)
end
end
list = Listener.new
xmlfile = File.new( "f:\\data2\\mloy\\out\\mtl009index.3.xml")
sparser = Parsers::StreamParser.new(xmlfile,list)
sparser.parse()
puts list.sum