unexpected behaviour in Pathname?

M

Matthew Smillie

I'm writing a quick script to selectively process some files, and I
found a bit of odd behaviour using Pathname#each and #each_entry,
which is best illustrated, rather than explained:

irb(main):001:0> require 'pathname'
=> true
irb(main):002:0> p = Pathname.new("/home/matt/test")
=> #<Pathname:/home/matt/test>
irb(main):003:0> p.entries.each{ |q|
irb(main):004:1* puts "operating on: #{q.dirname}/#{q.basename}"
irb(main):005:1> }
operating on: ./.
operating on: ./..
operating on: ./a
operating on: ./b
operating on: ./c

Now, the problem that results is that in the block, I can't do q.read
reliably (or indeed q.anything), because it's looking for q relative
to the current directory, when surely it should be looking relative
to p.

Apart from files not being found if you're not in the correct
directory, this could lead to more difficult-to-detect problems if
you have a structure like the following and run the script in a
directory which has identically-named files to the intended target,
for instance:

/home/matt/project/training/{1, 2, 3, 4, etc}
/home/matt/project/test/{1, 2, 3, 4, etc}

Since even when the directory to be processed is given as an absolute
pathname, its subdirectories are treated as relative pathnames.

I realise that I can solve this by doing (p + q).read inside the
block, but surely this isn't the desired behaviour of Pathname#each?

thanks,
matthew smillie.
 
M

Matthew Smillie

I'm writing a quick script to selectively process some files, and I
found a bit of odd behaviour using Pathname#each and #each_entry,
which is best illustrated, rather than explained:

Quick clarification: I do mean Pathname#entries rather than
Pathname#each.

Whoops.
 
T

Tanaka Akira

Matthew Smillie said:
I realise that I can solve this by doing (p + q).read inside the
block, but surely this isn't the desired behaviour of Pathname#each?

It is intended for consistency to Dir.entries.

Use Pathname#children instead.

Note that Pathname#children doesn't generates "." and "..".
I hope you don't need them.
 
R

Robert Klemme

Tanaka said:
It is intended for consistency to Dir.entries.

Use Pathname#children instead.

Note that Pathname#children doesn't generates "." and "..".
I hope you don't need them.

Another - possibly simpler - approach would be to use
Dir['/home/matt/test/*'].

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,275
Messages
2,571,375
Members
48,067
Latest member
MackenzieP

Latest Threads

Top