f



Iteration through File.file? misses entries for which File.file?(entry) == true

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?

Kyle
0
kyle (1)
8/2/2010 12:28:19 PM
comp.lang.ruby 48886 articles. 0 followers. Post Follow

10 Replies
9054 Views

Similar Articles

[PageSpeed] 19

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/.

0
Brian
8/2/2010 1:05:28 PM
Oh, and another hint: try things out in irb to find out what's 
happening.

/$ irb --simple-prompt
>> Dir.chdir("/")
=> 0
>> Dir.foreach("etc") { |x| puts x }
0
Brian
8/2/2010 1:07:00 PM
>>=20
>> def getFiles(dir)
>>    pwdFiles =3D Array.new
>>=20
>>    Dir.foreach(dir) do |entry|
>>        pwdFiles.push(entry) if File.file?(entry) =3D=3D true
>>    end
>> end
>>=20

The symbolic constant for truth is True, not true.

In either case, because File.file? returns either True or False, you can =
drop the comparison:


>> def getFiles(dir)
>>    pwdFiles =3D Array.new
>>=20
>>    Dir.foreach(dir) do |entry|
>>        pwdFiles.push(entry) if File.file?(entry)
>>    end
>> end


If this is truly a method in an object, though, bear in mind scoping =
issues. pwdFiles is only available inside this method definition. When =
you declare it in your intialize statement, prepend with a =
scope-changing symbol. The most common in this case is @

def initialize
    #will contain all file entries in the directory
    @pwdFiles =3D []
end

def get_files(dir)
    @pwdFiles =3D Array.new
   =20
    Dir.foreach(dir) do |entry|
        @pwdFiles.push(entry) if File.file?(entry) =3D=3D true
    end
end



And pay attention to the advice about camelCase versus snake_case for =
method names: because Ruby's duck typed, it's helped me out sometimes to =
be able to glance at my code and tell what is a variable and what isn't =
very quickly.

Best

James=

0
James
8/2/2010 1:21:05 PM
>         pwdFiles.push(entry) if File.file?(entry) == true

While not an answer to your question, I thought I'd comment on the line 
above -- you don't need to add the "== true".

pwdFiles.push(entry) if File.file?(entry)


A little more:

Now, this is just me, but I also try to avoid writing negative logic... 
if I wanted only the items where File.file?(entry) was false, I would 
write:

pwdFiles.push(entry) unless File.file?(entry)

instead of

pwdFiles.push(entry) if not File.file?(entry)
or
pwdFiles.push(entry) if File.file?(entry) == false



Please note: this is all just personal preference -- your code will work 
just fine. I only mention it as you indicated you were new, and I 
thought I'd share.


-- 
Posted via http://www.ruby-forum.com/.

0
Bob
8/2/2010 1:24:28 PM
James Harrison wrote:
> The symbolic constant for truth is True, not true.

That is incorrect, as 5 seconds with irb will show you.

$ irb --simple-prompt
>> true
=> true
>> True
NameError: uninitialized constant True
  from (irb):2

(You may have been thinking of TrueClass and FalseClass, perhaps?)

> In either case, because File.file? returns either True or False, you can 
> drop the comparison:

It returns true or false, but yes the comparison can be removed.

> If this is truly a method in an object, though, bear in mind scoping 
> issues. pwdFiles is only available inside this method definition. When 
> you declare it in your intialize statement, prepend with a 
> scope-changing symbol. The most common in this case is @
> 
> def initialize
>     #will contain all file entries in the directory
>     @pwdFiles = []
> end

@ is not a "scope changing symbol". @pwdFiles is an instance variable of 
the object, whereas pwdFiles is a local variable. They are completely 
different concepts.

Since the OP wanted to return the value from the getFiles method, and 
not set any instance variables in the object, then a local variable is 
appropriate here.
-- 
Posted via http://www.ruby-forum.com/.

0
Brian
8/2/2010 1:28:00 PM
If you're going to write an email and be wrong, be wrong on every point, =
that's what I was always taught and I'm sticking by it goddamit!

On Aug 2, 2010, at 7:28 AM 8/2/10, Brian Candler wrote:

> James Harrison wrote:
>> The symbolic constant for truth is True, not true.
>=20
> That is incorrect, as 5 seconds with irb will show you.
>=20
> $ irb --simple-prompt
>>> true
> =3D> true
>>> True
> NameError: uninitialized constant True
>  from (irb):2
>=20
> (You may have been thinking of TrueClass and FalseClass, perhaps?)

You're 100% correct. Total brainfart.


>=20
>> In either case, because File.file? returns either True or False, you =
can=20
>> drop the comparison:
>=20
> It returns true or false, but yes the comparison can be removed.


>=20
>> If this is truly a method in an object, though, bear in mind scoping=20=

>> issues. pwdFiles is only available inside this method definition. =
When=20
>> you declare it in your intialize statement, prepend with a=20
>> scope-changing symbol. The most common in this case is @
>>=20
>> def initialize
>>    #will contain all file entries in the directory
>>    @pwdFiles =3D []
>> end
>=20
> @ is not a "scope changing symbol". @pwdFiles is an instance variable =
of=20
> the object, whereas pwdFiles is a local variable. They are completely=20=

> different concepts.
>=20
> Since the OP wanted to return the value from the getFiles method, and=20=

> not set any instance variables in the object, then a local variable is=20=

> appropriate here.



In future, I'll have to stop myself whenever the thought "that mightn't =
be the right word" crops through my head. I figured it'd be close enough =
to get the idea across, but given that a symbol is actually a language =
construct I should've taken a few more seconds out.


In either case, you've hit something that interests me. Conceptually, =
I'd understood that the difference between an @-prepended variable and a =
non-@-prepended variable is that the former is global to the object, so =
it's not impacted by the change in scope introduced by defining a method =
inside the object. So I figured that describing the @ character as =
changing the internal scope of a variable from local to global inside =
the object wouldn't be entirely missing the mark. But it's possible I'm =
missing something.


Thanks for the clarifications and corrections, dude.=20

Best

James


0
James
8/2/2010 1:54:04 PM
Kyle Barbour wrote:
> def getFiles(dir)
>     pwdFiles = Array.new
> 
>     Dir.foreach(dir) do |entry|
>         pwdFiles.push(entry) if File.file?(entry) == true
>     end
> end

That can't work since Dir.foreach yields only the filenames of the files 
in the directory to the block, not the directory the files are actually 
in. So suppose you have:

dir/my_file
dir/my_second_file

By calling Dir.foreach("dir") you'll get "my_file" and "my_second_file". 
Your File.file? statement then checks for the presence of the filenames 
in the current working directory -- where they don't reside. Solution: 
Append "dir" to the filename.

def get_files(dir)
  pwd_files = Array.new

  Dir.foreach(dir) do |entry|
    path = File.join(dir, entry)
    pwd_files.push(path) if File.file?(path)
  end
  pwd_files
end

And please use snake_case for your method and variable names.

Marvin
-- 
Posted via http://www.ruby-forum.com/.

0
sutniuq (131)
8/2/2010 2:01:42 PM
James Harrison wrote:
> In either case, you've hit something that interests me. Conceptually, 
> I'd understood that the difference between an @-prepended variable and a 
> non-@-prepended variable is that the former is global to the object, so 
> it's not impacted by the change in scope introduced by defining a method 
> inside the object. So I figured that describing the @ character as 
> changing the internal scope of a variable from local to global inside 
> the object wouldn't be entirely missing the mark. But it's possible I'm 
> missing something.

They are different in both scope and lifetime.

Instance variables (@foo) are a property of the object instance itself, 
and once set, they remain for as long as the object exists, or until 
reassigned. Calls to methods of the same object will see the same value 
of @foo - even multiple concurrent calls in different threads.

Local variables are created in an activation record which is created 
when the method is invoked, and so the values are not tied to the object 
itself. If there are multiple calls to the method from multiple threads, 
they will have their own activation records, and so independent local 
variables. Normally the activation record is garbage-collected when the 
method returns.

Now, I'm not sure I should be complicating things here, but activation 
records may have extended lifetimes too, when closures are involved.

class Foo
  def initialize(n)
    @n = n
  end
  def make_adder(y)
    lambda { |x| y + x }
  end
end

f = Foo.new(1)    # #<Foo @n=1>

a1 = f.make_adder(10)
a2 = f.make_adder(20)
a1.call(3)        # 13
a1.call(4)        # 14
a2.call(5)        # 25

y is a local variable in make_adder, but it persists in the lambdas, 
even after make_adder has returned. The two lambdas, a1 and a2, have 
different values bound to y. But there is still only a single object of 
class Foo.

My apologies if this has confused matters further :-) But hopefully it 
highlights how different these things are.

Regards,

Brian.
-- 
Posted via http://www.ruby-forum.com/.

0
Brian
8/2/2010 2:15:42 PM
Thanks for all the responses! I feel so thoroughly helped :)

On Aug 2, 7:01=A0am, Marvin G=FClker <sutn...@gmx.net> wrote:
> By calling Dir.foreach("dir") you'll get "my_file" and "my_second_file".
> Your File.file? statement then checks for the presence of the filenames
> in the current working directory -- where they don't reside. Solution:
> Append "dir" to the filename.

Martin - thanks for the diagnosis, that makes perfect sense. Awesome.
That works very well and solves my problem!

On Aug 2, 6:05=A0am, Brian Candler <b.cand...@pobox.com> wrote:
> As an alternative, Dir["etc/*"] builds an Array directly. So you could
> have:
>
> def get_files(dir)
> =A0 Dir["#{dir}/*"].select { |x| File.file?(x) }
> end

Interesting, thanks! Is there any reason to prefer either this
solution or the one Martin gave in the above post?

Also: everyone, thanks for the newbie friendliness and for the general
advice (snake_case, negative logic, etc.). Thoroughly appreciated.

Kyle
0
Kyle
8/2/2010 8:09:14 PM
Kyle Barbour wrote:
> Interesting, thanks! Is there any reason to prefer either this
> solution or the one Martin gave in the above post?

I'd prefer the Dir[] variant, since it's more compact. And if you want 
to search for files via wildcards, it's the best way to go I think.

Oh, and one last note: My name is "Marvin", not "Martin". Note the v. 
;-)

Vale,
Marvin
-- 
Posted via http://www.ruby-forum.com/.

0
utf
8/2/2010 8:55:22 PM
Reply:

Similar Artilces:

file.exe file generation from file.m file
How to generate application (*.exe) file from *.m file, which has lots of graphics. Program was written for image watermarking by using image processing toolbox. I want to send this program some where else but with out sowing the program codes. By this *.exe no need to use matlab6.5 platform. Also tell me How to generate *.p file from *.m file Which is hide the code to user but for run this program need matlab6.5 Please give me some idea about it. it is very urgent for me. I will be very great full to you "Biswajit Kar" <hibiswajitkar@rediffmail.com> wrote in message ne...

multiple files into one file based on unique entry in one of the files
I have 4 flat files where each field is separated by a pipe |. In each file the second field has a unique value that is in all the files. Each line is terminated by a newline. I what to combine each file and create one file. In this one file, there should be one line for each "unique" entry in that was found in the second file. I was able to do this in MS access by creating each file as table and linking the "unique" field in the 2nd file to the other files. I want do this in Tcl, so I can automate the process. Come some please point me in a starting directio...

file extention from file file location
Hi, I am new to perl (only working on this one problem) but I program in other languages. We have an upload script written in cgi. Can anyone tell me how to get the file extension from the variable $File1 (actual file location on uploader's computer) then find out if it is equal to "txt" Thanks in advance for not telling me to read the manual. Ron -- PLEASE NOTE: comp.infosystems.www.authoring.cgi is a SELF-MODERATED newsgroup. aa.net and boutell.com are NOT the originators of the articles and are NOT responsible for their content. HOW TO POST to co...

Compare Two Text file and update files only for missing entries ...!!!
We have index file (.txt) at Repository folder(local machine) as well as at the destination(USB device). Each index file is having more than 30000 Entries. Index file entry contains Driver name, PnPID and Path of INF file. Here Single INF file can have multiple entries. when we copy the repository folder from Source location to Destination, first We need to Compare Two index Files. And find out the exact missing entries that are present in source index file but not in destination index file. And we need to update index file as well as copy only those files for missing entries at...

File share, File Sharing, File Host
http://fileuplo.de File share, File Sharing, File Host -- questo articolo e` stato inviato via web dal servizio gratuito http://www.newsland.it/news segnala gli abusi ad abuse@newsland.it ...

how to tell if a file is inary file or ascii file?
Hello, Is there a way to find if a file is a binary executable file or an ASCII executable file in unix? especially, if I have a file with permission of --x--x--x. Thanks, Peter peter wrote: > Hello, > > Is there a way to find if a file is a binary executable file or an ASCII > executable file in unix? especially, if I have a file with > permission of --x--x--x. If in a shell you could start with man file Tobias On Wed, 14 Jan 2004 05:31:11 +0000, peter wrote: > Is there a way to find if a file is a binary executable file or an ASCII > executable file in...

write file + input file + write file
Hi, I want to write some latex command to a file (file1), input the file at the end of the document. These command shall write to another file (file2) and at a second run I use the file2. Whatever I have tried nothing works and I don't known why. The goal is to save a set of special commands and run them at the end of the document, because they use some values which are only available at the end! Can anybody please help me with that? Thanks in advance! I should be something like: \begin{document} \usepackage{style} \input{file2} %file exists from a previous run \end{document} style.sty:...

How to copy a file to a file with a prefixed file name
I'm trying to write a program that will archive selected files to an archive directory. The files in the archive directory will have a prefix in the format yyyymmdd-hhmmss-filename.ext. So, if the file is called "somefile.dat", then the filename in the archive directory should be "20090522-164325-somefile.dat". I'm using Clipper's COPY FILE command to do the copy. I can't figure out how to get the prefix in front of the file name. Creating the prefix string is no problem, but I can't figure out how to tack that onto the front of the filename. If I...

object files, header files, source files?
I can't find any books describing the anatomy of C/C++ programs. What is an object file? Can it be generated from a header file?, what is linking?, why does a source file need an object file? etc. I have looked in The C programming Language, The C++ Programming Language, Accelerated C++, GNU make etc but they don't describe these basic subject. Any literature that covers these subjects? saneman wrote: > I can't find any books describing the anatomy of C/C++ programs. What is > an object file? Can it be generated from a header file?, what is > linking?, why does a s...

Text files read multiple files into single file, and then recreate the multiple files
Hiya, The title says it all really, but im a newbie to python sort of. I can read in files and write files no probs. But what I want to do is read in a couple of files and output them to one single file, but then be able to take this one single file and recreate the files I put into it. Im really at a loss as to how I go about recovering the files? obviously if i scan for a string that specifys the start and end of each file, theres the chance that the file might contain this term to which would split the files into unwanted chucks of file, which wouldnt be wanted. Any ideas? code snippets...

Execute ruby file from a ruby file
Hi, I can't find out how can I execute my ruby script from another ruby file. This is how I would do it in command line ruby jobs/eventParser.rb "5454353" Greg -- Posted via http://www.ruby-forum.com/. On Tue, Jun 15, 2010 at 1:35 PM, Greg Ma <gregorylepacha@msn.com> wrote: > Hi, > I can't find out how can I execute my ruby script from another ruby > file. > > This is how I would do it in command line > ruby jobs/eventParser.rb "5454353" ri Kernel#system ---------------------------------------------------------- ...

How to execute ruby file from other ruby file?
How to execute ruby file from other ruby file? Thanks! -- Posted via http://www.ruby-forum.com/. ------=_Part_3087_10746843.1136909690107 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline require 'filename' you're welcome 2006/1/10, Szczepan Faber <szczepiq@gmail.com>: > > How to execute ruby file from other ruby file? > > Thanks! > > -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_3087_10746843.1136909690107-- Dirk Meijer wrote: > require 'filename&...

Library .so file missing, but I have the .a file
Not sure I understand the difference between a .a and .so library file. I installed ntop on my x86 Solaris 10 system. Running ntop them complains that libpcap.so does not exist. However, I do notice that libpcap.a exists in /opt/sfw/lib, just not libpcap.so. Also, I do have /opt/sfw/lib on my LD_LIBRARY_PATH variable. Nevertheless, I grabbed libpcap from sunfreeware and installed it into /usr/local. This package also only contains libpcap.a, not libpcap.so. Is there a way to generate a .so object from the .a file? Thanks, -Bob Andover, MA In article <a63ee612-e95d-4d55-aa75-66b9e7c9c...

Offline Files Missing Files
Hi, I'm trying to get a laptop going with offline files. I have a share of ca. 4 GB and I want all of this to be available offline on the laptop. I have offline files enabled and it all seems to work fine. Fine, apart from the fact that it isn't all available in the offline copy! After a lot of searching, I did find the option to change the amount of space to allocate for offline files (default is 10% of drive, or 3 GB in this case). Changing the allocated amount doesn't seem to make any difference: there are stil lots of files missing when offline! Looking in the Of...

Web resources about - Iteration through File.file? misses entries for which File.file?(entry) == true - comp.lang.ruby

Fixed-point iteration - Wikipedia, the free encyclopedia
which gives rise to the sequence which is hoped to converge to a point . If is continuous, then one can prove that the obtained is a fixed point ...

All sizes - Android: A problem of fragmentation or iteration? - Flickr - Photo Sharing!
Flickr is almost certainly the best online photo management and sharing application in the world. Show off your favorite photos and videos to ...

Music from very short programs - the 3rd iteration - YouTube
Very short C programs and Javascript expressions generating musical output. This is the third video in the series. More info: http://counter ...

Iteration for innovation: CJF J-Talk on disruption in journalism
When it comes to innovation, what’s next for news organizations in terms of content, strategy and advertising? As Eric Mark Do reports, Michael ...

The Porsche 911: An ode to iteration
... its 50th anniversary . What an incredible run. The 911 has always served as special inspiration to those who believe in long-term iteration. ...

Iterations Stories and Velocity
Mishkin Berteig is a Baha'i, a father of four, a husband and an experienced Agile consultant and trainer. Mishkin is a Certified Scrum Trainer ...

Learning Scrum Through Games – Golidocks Iteration II
Last year I created a short session – Learning Scrum Through Games – to help people explore the basics of Scrum in a one hour format. This year ...

Next Iteration iPhone on Track for September Launch? - John Paczkowski - Mobile - AllThingsD
Dust off the urban camping gear. The next iteration of the iPhone is reportedly on track for a September launch.

Hillary's latest iteration preaches 'love and kindness'
It was during the 2008 election that Hillary Clinton portrayed herself as the hard-hitting person America needed in the White House to answer ...

Server login considered harmful – the next iteration
Patrick Debois and Jeffrey Fredrick asked if I could blog about improvements I was making to our presentation “Server Login Considered Harmful” ...

Resources last updated: 2/8/2016 1:21:45 PM