From: lists@... Date: 2009-07-24T01:35:07+09:00 Subject: Re: Dir.entries, output showing nils On Fri, Jul 24, 2009 at 01:23:27AM +0900, Rob Biedenharn wrote: > On Jul 23, 2009, at 11:42 AM, Mmcolli00 Mom wrote: >> When I output to line for RegisteredUser it shows all filenames as nil >> for all but the files. What can I change to show only the filename >> meeting the conditions? >> Thanks, MC >> >> outputs.... >> nil >> nil >> nil >> nil >> AUR123443.txt >> >> Dir.entries(ascpath).each do |filename| >> >> if filename =~ /^AU/ then >> if filename[2..2] == "R" then >> RegisteredUser = filename >> else >> NonRegisteredUser = filename >> end >> end >> >> #below shows nil for all files and then shows the registereduser file. >> puts RegisteredUser >> >> end >> -- Posted via http://www.ruby-forum.com/. > > > First, Capitalized names in Ruby are constants. You probably want a > local_variable instead. > > I'm not sure from your example and question what you really want, but > here are some options: > > # An array of filenames that start with AU > files = Dir.glob("AU*") # or Dir["AU*"] > > # Split one array into a pair of arrays (in another array) based on a > condition: > files.partition {|filename| filename[2..2] == "R"} > > (which is Enumerable#partition) > > Does that help? > > -Rob > > Rob Biedenharn http://agileconsultingllc.com > Rob@AgileConsultingLLC.com > He's also defining it inside the 'each' which, I believe, localizes the variable. Thus, it will be nil at the beginning of each loop. If not set (i.e. the file does not match), it will be nil, as he is saying now. Seems to me you want something more like this: if filename =~ /^AUR/ then puts filename end It should also be noted that you do not need to say [2..2] if you want the 3rd char of a string, just [2] will do. HTH, - Kyle