On 21 Aug 2007, at 15:57, Rebhan, Gilbert wrote:

>
> Hi,
>
> -----Original Message-----
> From: dima [mailto:dejan.dimic / gmail.com]
> Sent: Tuesday, August 21, 2007 8:50 AM
> To: ruby-talk ML
> Subject: Re: Test if file is binary ?
>
> On Aug 21, 8:04 am, "Rebhan, Gilbert" <Gilbert.Reb... / huk-coburg.de>
> wrote:
>> Hi ,
>>>
>>> how to test if a file is binary or not ?
>>>
>>> There ain't something like File.binary =
>>> NoMethodError: undefined method `binary?' for File:Class
>>>
>>> Any ideas or libraries available ?
>
>> What to you need to achieve with this is_binary? method?
>> All files are just collection of bytes, so in a perspective they all
>> are binary. We interpret them as suites our needs.
>
> For example this information is needed to decide whether
> cvs should handle that file / that fileextension as binary or ascii
>
> Regards, Gilbert

One simple approach is this:

class File
   def is_binary?
     ascii = 0
     total = 0
     self.read(1024).each_byte{|c| total += 1; ascii +=1 if c >= 128  
or c == 0}
     ascii.to_f / total.to_f > 0.33 ? true : false
   end
end

You can tweak the 0.33 value if you like. Probably better (i.e. more  
robust) ways out there though.

Alex Gutteridge

Bioinformatics Center
Kyoto University