From: Mark Wilson Date: 2003-08-01T14:09:14+09:00 Subject: Re: A bundle of newbie queries On Friday, August 1, 2003, at 12:26 AM, Gawnsoft wrote: > [snip] > > I have some fresh and queries and problems though - > > 1) After the file has been opened and I've iterated through it once, I > can't successfully iterate through the opened file for something else. > e.g. > > dictionary2 = Hash.new(0) > > aFile.each_line { | eachLine | dictionary2[ /[0-9.]+/ ] = > dictionary2[ /[0-9.]+/ ] + 1 if eachLine.include?("anotherfile") } The prior answer applies to the following: File.open("filename") { |f| f.each_line etc. ... } which automatically closes the file after the block is executed. In your example, the file "reader" is now at the end of the file (try aFile.pos to see the line number). To go back to the beginning, you can use aFile.rewind. If you have the memory available, you could use: stringArray = File.open("filename") { |f| f.readlines } which returns an array consisting of the lines in the file. The array does not need to be rewound to use its contents again. > 2) I then tried to get the no-longer usable file garbage-collected by > IRB-ing > > aFile = nil > > but even after evaluating this statement, another windows app still > fails to be able to over-write copyOfGeneral.txt > > What should I do to get Ruby to 'free up' the file? aFile.close should do the trick. > 3) I tried to cut it down from 4 lines of code to 3 lines of code by > using: > (File.open("d:/Data/Logs/Savant/copyOfGeneral.txt")).each_line { > |line| blah... } File.open returns a File object and not the contents of the file. The following should work (although you may need to work on it): File.open("filename") { |f| f.each_line { |line| do stuff} } > I'm sure I've seen snippets of code in the newsgroup that call methods > from the result of called methods, although the real reason I tried it > is because I'm currently learning Smalltalk where > > ( File open: "name of aFile" ) each_line: [ blah... ] # > pseudocode only this, in all probability, btw > > works as the parenthesised expression is evaluated first and returns > aFile, which is then sent the eac_line message > > What are the rules as to when object.method.method is a valid > Ruby construct? Is it ever a valid Ruby construct? Chaining methods works when the result of the first method (the value returned) can respond to the next method in the chain. It's a perfectly valid Ruby construct and one of my personal favorites. But beware of methods that return nil or an unexpected value (for example, an_array.delete(element) returns nil if the element is not in the array and returns the element deleted if is in the array). By the way, the work around for the nil part of this is: a.delete(element) {a} which returns the array if the element is not in the array. [snip] The reference part of the pickaxe book usually (as I recall) specifies what a method returns. Regards, Mark