Wednesday, November 22, 2006

[temp] Pages 123-4: Writing to files


Listen to this article.

Value: Medium

Level: Hard

Summary:
When you use puts and print to output, every object is converted to a string (note that nil is passed as "nil,", an array is passed as separate elements, a non-valid string is passed as object'class name and ID). To write binary data you can use IO#print() passing a string with the bytes. To get binary data into string you can use a literal, poke it in byte by byte, or use Array#pack(). You can use Array#<<() to append an object to an output IO stream. StringIO objects behave just like other I/O objects, but they read and write strings, not files.

Memo: None

Esample:

str1 = "\001\002\003" → "\001\002\003"
str2 = ""
str2 << 1 << 2 << 3 → "\001\002\003"
[ 1, 2, 3 ].pack("c*") → "\001\002\003"

require 'stringio'
ip = StringIO.new("now is\nthe time\nto learn\nRuby!")
op = StringIO.new("", "w")
ip.each_line do |line|
op.puts line.reverse
end
op.string → "\nsi won\n\nemit eht\n\nnrael ot\n!ybuR\n"

Reported errata (at 10/17/06 14:17:18 PDT): 0

Errata I found: 0

My suggestions to the author: 0

0 Comments:

Post a Comment

<< Home