So far, we've been merrily calling
puts
and
print
,
passing in any old object and trusting that Ruby will do the right
thing (which, of course, it does). But what exactly
is it doing?
The answer is pretty simple. With a couple of exceptions, every object
you pass to
puts
and
print
is converted to a string
by calling that object's
to_s
method. If for some reason
the
to_s
method doesn't return a valid string, a string is
created containing the object's class name and id, something like
<ClassName:0x123456>
.
The exceptions are simple, too. The
nil
object will print as the
string ``nil,'' and an array passed to
puts
will be written
as if each of its elements in turn were passed separately to
puts
.
What if you want to write binary data and don't want Ruby messing
with it?
Well, normally you can simply use
IO#print
and pass
in a string containing the bytes to be written. However, you can
get at the low-level input and output routines if you really
want---have a look at the documentation for
IO#sysread
and
IO#syswrite
on page 335.
And how do you get the binary data into a string in the first place?
The two common ways are to poke it in byte by byte or to use
Array#pack
.
str = ""
|
� |
""
|
str << 1 << 2 << 3
|
� |
"\001\002\003"
|
|
[ 4, 5, 6 ].pack("c*")
|
� |
"\004\005\006"
|