Forum: Ruby ruby way of dumping file

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Joshua B. (Guest)
on 2008-12-17 07:19
(Received via mailing list)
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.
The H. (Guest)
on 2008-12-17 07:50
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]
Einar Magnús Boson (Guest)
on 2008-12-17 08:10
(Received via mailing list)
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
Peña, Botp (Guest)
on 2008-12-17 08:34
(Received via mailing list)
From: Joshua B. [mailto:removed_email_address@domain.invalid]
# 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
Brian C. (Guest)
on 2008-12-17 13:43
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(" ")
This topic is locked and can not be replied to.