From: Robert Klemme Date: 2011-05-30T20:00:24+09:00 Subject: Re: Variable scopes with code blocks. On Sat, May 28, 2011 at 4:14 AM, Justin Collins wrote: > On 05/27/2011 03:22 PM, Patrick Lynch wrote: >> >> Hello! >> >> Novice here. I'm reading Beginning Ruby and Beginning Rails by Apres and >> building both applications they walk you through. Additionally, I'm >> taking courses at lynda dot com and attempting to build a simple >> application myself. >> >> That said, I'm aware of the limits you have with local variable being >> incapable of accessing variables defined inside of a code block, but is >> there any exception to this rule? >> >> Example: >> _____________ >> >> 1.times do >>   File.open("text.txt").each {|a| puts a} >> end >> >> puts a >> # This where I get my error. >> _____________ >> >> Is there anything I can do to 'puts a' that will allow it to return the >> content it was passed inside of the code block? >> >> Ultimately, I'd like to store the 'text.txt' as an array so I can call >> .uniq! on it... But we don't need to get into that in this thread. > In light of your ultimate goal, consider using File.readlines("text.txt") > [1]. Or rather File.foreach. File.readlines should only be used if you need all lines of the file in memory for example because you need to go through them multiple times and you know the file is not too large. For making lines unique there are different options available depending on the fact whether the order is important. I find the first one the most elegant: # order doesn't matter && we are on 1.9 require 'set' unique = File.foreach("text.txt").to_set # order does matter or on 1.8.6 or earlier require 'set' set = Set.new unique = [] File.foreach("text.txt") {|l| unique << l if set.add? l} Or, a bit more involved: h = Hash.new [] File.foreach("setup.log") {|l| h.fetch(l) {h[l] = h.default << l}} unique = h.default You can also use a variant of what I once proposed: http://viewsourcecode.org/why/redhanded/bits/klemmeSSilentHash.html h = {} unique = File.foreach("text.txt").inject([]) {|a,line| h[line] ||= a << line} ... > Also note that in your example you are opening the file without ever closing > it. If you pass a block to File.open(), it will ensure the file is closed > [2]. +1! > [1] http://rdoc.info/stdlib/core/1.9.2/IO.readlines > [2] http://rdoc.info/stdlib/core/1.9.2/File.open Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/