puts vs. write for writing to a file

R

Randy Kramer

I've done some googling, some looking in the pickaxe(2) book (using the
index), and some experimenting in irb, but I can't readily see the difference
between puts and write (except that write doesn't work in all cases in irb:)

irb(main):044:0> write "\nmorF\n\n"
NoMethodError: undefined method `write' for main:Object

So what is the difference (specifically for the case of writing to a file)
and/or when should I use one vs. the other?

Randy Kramer
 
A

Alex Young

Randy said:
I've done some googling, some looking in the pickaxe(2) book (using the
index), and some experimenting in irb, but I can't readily see the difference
between puts and write (except that write doesn't work in all cases in irb:)

irb(main):044:0> write "\nmorF\n\n"
NoMethodError: undefined method `write' for main:Object

So what is the difference (specifically for the case of writing to a file)
and/or when should I use one vs. the other?
On a File object (actually, they're defined on IO), write just writes
the string given to the file unchanged. IO#puts adds a newline at the
end of the string if there isn't one already.
 
R

Randy Kramer

On a File object (actually, they're defined on IO), write just writes
the string given to the file unchanged. IO#puts adds a newline at the
end of the string if there isn't one already.

Ahha, thank you very much!

(Now, knowing that, I can see it in the pickaxe-- I guess there were too many
other wording differences between the two for me to quickly spot the
significant (for me) difference. For example, puts (on page 512) is
described in terms of writing an object, while write (page 515) is described
in terms of writing a string.)

Randy Kramer
 
R

Robert Dober

On a File object (actually, they're defined on IO), write just writes
the string given to the file unchanged. IO#puts adds a newline at the
end of the string if there isn't one already.
Furthermore puts formats array instances as follows

array_instance.join("\n").

Robert
 
C

Chad Perrin

On a File object (actually, they're defined on IO), write just writes
the string given to the file unchanged. IO#puts adds a newline at the
end of the string if there isn't one already.

I guess the next question, then, is "What's the difference between print
and write for writing to a file?"

Trying to answer my own question with irb, I see that a successful write
has a return value equal to the number of characters it writes to the
file, while a successful print returns nil. Is that the only difference
in a file writing context?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top