From: Robert Klemme Date: 2005-01-20T21:21:00+09:00 Subject: Re: Confused about variable "declarations" "Graham Nicholls" schrieb im Newsbeitrag news:1106221017_4840@surge1-maxim.com... > > Page 14 of the new Pickaxe book says (amongst other things): > > "Note that we didn't have to declare the variable 'result'; it sprang into > existence when we assigned to it." > > This was my understanding, but I keep seeing this sort of thing: > > ./duprop:136:in `find_pcap_offset': undefined local variable or method > `offset' for # (NameError) > > when I run this: > > offset=line.split()[1].to_i > > Its easily fixed: I assign 0 to offset earlier in the method: > > def find_pcap_offset # Find the offset to the pcap entry for printer_name > found=false > offset=0 # <- This fixes things. > begin > pcap_file=File.open(@pcap_fname) > rescue IOError > print("can't open pcap file #{@pcap_fname}\n") > exit(BAD_PCAP_FILE) > end > # OK, now find the pcap entry > pcap_file.each_line() do |line| > if line.match(@printer_name) > print("Found printer #{@printer_name} in [#{line}]\n") if $debug > found=true > offset=line.split()[1].to_i > break Is this really the complete example? Because from what I see 'offset' is not read accessed here. Which line causes the error? Maybe you print out 'offset' after the each_line loop and no line matched. And btw, I'd rearrage the code like this (I know that you don't need to because of exit but if exit changes behavior i.e. not really exiting the system you might see surprising results): def find_pcap_offset # Find the offset to the pcap entry for printer_name found=false offset=0 # <- This fixes things. begin pcap_file=File.open(@pcap_fname) # OK, now find the pcap entry pcap_file.each_line() do |line| if line.match(@printer_name) print("Found printer #{@printer_name} in [#{line}]\n") if $debug found=true offset=line.split()[1].to_i break ... end ... end rescue IOError $stderr.print("can't open pcap file #{@pcap_fname}\n") exit(BAD_PCAP_FILE) end Or leave the exception handling completely out here. IHMO the exception is meaningful enough: 13:17:42 [otrs-1006999]: ruby -e 'def find_pcap_offset() File.open("x") {} end; find_pcap_offset' -e:1:in `initialize': No such file or directory - x (Errno::ENOENT) from -e:1:in `open' from -e:1:in `find_pcap_offset' from -e:1 > Now I hate to do this - partly at least 'cause its clear evidence I don't > understand something! The error can only occur if you read access the var before writing it. Kind regards robert