Ruby way of dumping file

Hi,
Can someone give me a cleaner, more rubyesque (even correct) way of
printing
out the first 20 bytes of a file? My solution doesn’t feel right.

open(ARGV[0], ‘rb’) { |f|
(0…20).each do |n|
printf "%02d: ", n
f.read(1).each_byte { | b | printf “0x%02x \n”, b }
end
}

Thanks.

Joshua B. wrote:

Hi,
Can someone give me a cleaner, more rubyesque (even correct) way of
printing
out the first 20 bytes of a file? My solution doesn’t feel right.

print File.read(ARGV.first)[0…20]

On 17.12.2008, at 05:42 , The Higgs bozo wrote:

Joshua B. wrote:

Hi,
Can someone give me a cleaner, more rubyesque (even correct) way of
printing
out the first 20 bytes of a file? My solution doesn’t feel right.

print File.read(ARGV.first)[0…20]

Posted via http://www.ruby-forum.com/.

Doesn’t that read the entire file before extracting the first 20
bytes? Seems silly to me.

rather something like this:

open ARGV.first, “rb” do |f|
read = “”
begin
read += f.read(20)
end while read.size < 20 && !f.eof?
p read[0…20]
end

although I suppose this would work too:

p open(ARGV[0], “rb”){|f|f.read(20)}

but I don’t think read(20) is guaranteed to read 20 bytes but maybe
that is just in sockets.

einarmagnus

From: Joshua B. [mailto:[email protected]]

Can someone give me a cleaner, more rubyesque (even correct)

way of printing out the first 20 bytes of a file? My solution

doesn’t feel right.

open(ARGV[0], ‘rb’) { |f| …

try,

IO.read ARGV[0], 20

Einar Magnús Boson wrote:

p open(ARGV[0], “rb”){|f|f.read(20)}

but I don’t think read(20) is guaranteed to read 20 bytes but maybe
that is just in sockets.

In Ruby, I believe it’s guaranteed to read 20 bytes, from both files and
sockets - it will restart the underlying OS calls if necessary - unless
EOF is reached.

I think the each_byte approach is cleanest, but here are some
alternatives:

not ruby-1.9 clean

puts File.read(ARGV[0],20).gsub(/(.)/) { “0x%02x\n” % $1[0] }

different output format

puts File.read(ARGV[0],20).unpack(“H*”)[0].scan(/…/).join(" ")
puts File.read(ARGV[0],20).unpack("H2 “*20).join(” ")