From: Bryan JJ Buckley Date: 2008-05-30T00:55:49+09:00 Subject: Re: How can a code block access an object's variables? --------------030506000202020809000006 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit You can pass arguments to block.call which can then be accessed by the block. block.call(line) And then when when calling your method, use my_reader.each_line do |myline| # myline holds the value of "line" puts myline end There's a decent introduction to blocks in the Pickaxe book. (http://whytheluckystiff.net/ruby/pickaxe/html/tut_containers.html) Jacob Rubynovice wrote: > Dear Rubyists, > > I am a novice Ruby developer who is interested in figuring out a way to > design something like what is demonstrated below. The reason why > each_line would not work in this example is because when you pass a > block of code to the FileReader object, the memory (members of > FileReader) is not shared with the block of code that is sent to > FileReader. > > Maybe I have the wrong idea for how this would be designed. I just > think it would be very convenient to do this sort of thing because I > could re-use the code to open a file and read lines and only pass it > code blocks pertainant to what I want to do with those lines of code. > > Please note that I do not only want to do this for an open file/read > line script. It would also be useful if you were expanding an IP range > that exceeds what you could store into an array object because you could > write an each_host method that takes in a block of code that relates to > what you want to do to each host. > > class FileReader > > def initialize(fname, &block) > @filename = fname > end > def each_line(&block) > begin > source = File.new(@filename, "r") > rescue => err > exit > end > begin > while(line = source.readline) > > line.strip! > if((line == "") || (line =~ /[\t+\s+]/)) > next > end > block.call > end > rescue EOFError > source.close > rescue => err > puts "[!] #{err}" > exit > end > end > > end > my_reader = FileReader.new(ARGV[0]) > my_reader.each_line { puts line > # do more parsing stuff here > } > --------------030506000202020809000006 Content-Type: text/x-vcard; charset=utf-8; name="jj.vcf" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="jj.vcf" YmVnaW46dmNhcmQNCmZuOkpKIEJ1Y2tsZXkNCm46QnVja2xleTtKSg0Kb3JnOlRyYXZlbCBJ USBHbWJIDQphZHI6Ozs7Ozs7RGV1dHNjaGxhbmQNCmVtYWlsO2ludGVybmV0OmpqQHRyYXZl bGlxLmRlDQp0ZWw7d29yazorNDkzMDY5MjA1MTI5Mg0KdGVsO2ZheDorNDkzMDY5MjA1MTI5 OQ0KdGVsO2NlbGw6KzQ5MTczMTc0NDE3NQ0KeC1tb3ppbGxhLWh0bWw6VFJVRQ0KdmVyc2lv bjoyLjENCmVuZDp2Y2FyZA0KDQo= --------------030506000202020809000006--