From: Brian Candler Date: 2010-08-02T22:05:28+09:00 Subject: Re: Iteration through File.file? misses entries for which File.file?(entry) == true Kyle Barbour wrote: > Hello everyone, > > I'm new to Ruby, so I'm most likely making an elementary mistake. > However, searching Google didn't help me find my answer, and after > mucking around with irb I still haven't figured it out. > > I wrote a method that was intended to take all of the files in a given > directory and put them into an array. Here's the code I wrote: > > def getFiles(dir) > pwdFiles = Array.new > > Dir.foreach(dir) do |entry| > pwdFiles.push(entry) if File.file?(entry) == true > end > end > > This works fine when called on the working directory --- that is, > getFiles(Dir.pwd). However, when I call it on a subdirectory --- for > example, getFiles("doc") --- it only returns one file. I tested to > make sure that the files being ignored in the subdirectory actually > gave "true" when tested with File.file?(entry), which they do. > > Anyone know what I'm doing wrong? I'm guessing you need to add this line to the end of your method: return pwdFiles or just pwdFiles since the return value of a method is the value of the last expression evaluated. As an alternative, Dir["etc/*"] builds an Array directly. So you could have: def get_files(dir) Dir["#{dir}/*"].select { |x| File.file?(x) } end (Aside: getFiles works fine, but get_files is a more conventional Ruby method name. Use CamelCase for constants/classes) -- Posted via http://www.ruby-forum.com/.