From: Tim Hunter Date: 2006-03-22T08:58:50+09:00 Subject: Re: Newbie: Better way to check a magic number on a file? Wes Gamble wrote: > All, > > I am trying to determine if I am dealing with an Excel file that I > upload to a Web server. > > Here is the first test - to verify the magic number of the file that I > have: > > #Check the magic number first to see if it's even an Office file > > magic_number = nil > File.open(path_to_file, "r") do |f| > magic_number = f.read(6) > end > return false unless > magic_number.unpack('H*').to_s().eql?('d0cf11e0a1b1') > > This seems a little bit less than optimal. I have to unpack my string > into an array and then reconvert it back to a string to compare it? > > Surely there is a simpler way? > > Should magic_number.eql?('d0cf11e0a1b1') work? > > Wes > I'm guessing the magic number is constant? Why not construct a constant string that is the magic number and then compare the bytes you get from the file to that string? Simple, fast, and ez-to-read. MAGIC_STRING = [0xd0,0xcf,0x11,0xe0,0xa1,0xb1].pack('c*').freeze if magic_number == MAGIC_STRING ...