It seems that on OS X, Dir.foreach doesn’t like to play nice with deleting things. The problem is, when it fills its array it also includes those little hardlinks in every directory . and .. as well as the .DS_STORE 
Unfortunately, Ruby doesn’t like to delete those, they tend to be owned by some other-worldy daemon in the OS X system. I don’t know this occurs the same in all systems, but I suspect that all systems do have such independent-minded things hanging around in directories. Being what they are, they only exist in most directories as proof of quantum-mechanics anyway…
In my inquisition, I found that:
Dir.glob("*").each { |f| File.delete(f) }
works better
(or any variation thereof)
del_list = Dir.glob("*")
del_list.each {|f| File.delete(f) }
or using do-end with more feedback at the proper moments via puts.
using Dir.glob only picks up files of the cooperative persuasion for its array! Meaning it doesn’t pay attention to those ninnies:
. .. and .DS_STORE
While poking around with this stuff earlier I did this and discovered such behavior:
# Directory listing, should work anywhere...
e_pwd = Dir.entries(Dir.pwd).join(" | ")
# Same thing, slightly lazier, but maybe not portable to other platforms
e_dot = Dir.entries(".").join(" | ")
# Same with just a iterated walk through the dir
foreach = Dir.foreach(Dir.pwd) do |f|
puts f
end
# Even more concise:
puts Dir["*"] # Dir[Dir.pwd] seems to only print pwd, not make our desired array of contents!
# Almost the same thing, using a pattern match with .glob, doesn't print . or ..
glob_star = Dir.glob("*").join(" | ")
puts "is e_pwd same as e_dot? #{e_pwd.eql?(e_dot)}"
puts "is e_pwd same as glob_star? #{e_pwd.eql?(glob_star)}"
puts e_pwd.gsub(glob_star, '') # shows the difference between them
So to make a long boring post longer, if you see anything here that I’m missing the point of or I should be thrown into a dungeon for, let me know!
P.S. This comes from working through Peter Cooper’s Beginning Ruby (any other programming language and the title might have to be changed like: Begging Java, Begging C++) and with e-mailing aforementioned scribe about the preceding mishmash of bibble-babble in Ruby.
0 comments ↓
There are no comments yet...Kick things off by filling out the form below.
Leave a Comment