Disappearing hash values?

mailbox = File.open(mbox)
mailbox.each_line {|line|
linecount += 1
mboxArray.push line
if line.include?(“filename=”)
haveattach = TRUE
filename = line.gsub(“Content-Disposition: attac
hment;”, ‘’)
filename = filename.gsub(“filename=”, ‘’)
filename = filename.gsub(/"/, ‘’)
filename = filename.gsub(/^ /, ‘’)
filename = filename.chomp + “.b64”
filehash = {filename => linecount-2}
print "filehash[filename] is: " + filehash[filen
ame].to_s + “\n”
#prints 183 the first time through the file
end

     if ( line.include?("--(null)") && haveattach )
         print "filehash[filename] is: " + filehash[filen

ame].to_s + “\n”
#this is now nil for some reason
print "linecount is: " + linecount.to_s + “\n”
length = linecount-filehash[filename]
filehash = {filename => length}
haveattach = FALSE
end
}

why does the value of filehash[filename] disappear in the second “if”?

On 5/24/06, newbie [email protected] wrote:

why does the value of filehash[filename] disappear in the second “if”?

An if statement introduces a new scope, so the filehash in the first
if is not available inside the second if. If you move the creation of
the hash outside both ifs and then just update it within the first if,
it will work as you expect.

Ryan

Ryan L. wrote:

On 5/24/06, newbie [email protected] wrote:

why does the value of filehash[filename] disappear in the second “if”?

An if statement introduces a new scope, so the filehash in the first
if is not available inside the second if. If you move the creation of
the hash outside both ifs and then just update it within the first if,
it will work as you expect.

Ryan

i need to update it in both ifs though
i need to put a starting line and an ending line

On 5/24/06, newbie [email protected] wrote:

i need to update it in both ifs though
i need to put a starting line and an ending line

Does this work (I can’t test it myself right now)?

filehash = {}
mailbox.each_line {|line|
linecount += 1
mboxArray.push line
if line.include?(“filename=”)
haveattach = TRUE
filename = line.gsub(“Content-Disposition: attachment;”, ‘’)
filename = filename.gsub(“filename=”, ‘’)
filename = filename.gsub(/"/, ‘’)
filename = filename.gsub(/^ /, ‘’)
filename = filename.chomp + “.b64”
filehash[filename] = linecount-2
print "filehash[filename] is: " + filehash[filename].to_s +
“\n”
#prints 183 the first time through the file
end

    if ( line.include?("--(null)") && haveattach )
        print "filehash[filename] is: " + filehash[filename].to_s + 

“\n”
#this is now nil for some reason
print "linecount is: " + linecount.to_s + “\n”
length = linecount-filehash[filename]
filehash[filename] = length
haveattach = FALSE
end
}

Besides declaring “filehash” outside the ifs, I made a few minor
alterations, replacing the “filehash = {filename => …}” statements
with “filehash[filename] = …”. The way it was before meant you were
throwing away the values previously stored in the hash every time that
line was executed.