🕷 zenspider.com

by ryan davis



sitemap
Looking for the Ruby Quickref?

I miss perl's -B

Published 2006-08-18 @ 00:59

Tagged toys, ruby

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:

1
2
3
4
5
6
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:

1
2
3
4
Find.find dir do |f|
  next if File.binary? f
  # ... process text files only ...
end