Method: File.binary?

Defined in:
lib/ptools.rb

.binary?(file) ⇒ Boolean

Returns whether or not file is a binary file. Note that this is not guaranteed to be 100% accurate. It performs a “best guess” based on a simple test of the first File.blksize characters.

Example:

File.binary?('somefile.exe') # => true
File.binary?('somefile.txt') # => false

– Based on code originally provided by Ryan Davis (which, in turn, is based on Perl’s -B switch).

Returns:

  • (Boolean)


93
94
95
96
# File 'lib/ptools.rb', line 93

def self.binary?(file)
  s = (File.read(file, File.stat(file).blksize) || "").split(//)
  ((s.size - s.grep(" ".."~").size) / s.size.to_f) > 0.30
end