This post originated from an RSS feed registered with Ruby Buzz
by Ryan Davis.
Original Post: I miss perl's -B
Feed Title: Polishing Ruby
Feed URL: http://blog.zenspider.com/index.rdf
Feed Description: Musings on Ruby and the Ruby Community...
Perl has a bunch of tests in form of -X path (e.g., -f path returns true if path exists and is a file). We have a direct analog with the test method (e.g., test ?f, path). The one we're missing is -B, which tests whether or not a file is (probably) a binary file. It is great for things like Find-based scripts. Recently I needed it for a script I was writing so I didn't have to keep adding file extensions I didn't want to process. Here it is:
class File
def self.binary? (path)
s = (File.read(path, 4096) || "").split(//)
((s.size - s.grep(" ".."~").size) / s.size.to_f) > 0.30
end
end
Now you can write things like:
Find.find dir do |f|
next if File.binary? f
# ... process text files only ...
end