tags:

views:

640

answers:

3

What's the difference between...

File.open('abc', 'w') { |f| f.puts 'abcde' }

...and...

File.open('abc', 'w') { |f| f.write 'abcde' }

...?

+10  A: 

puts appends a newline, write does not. Technically, puts appends the record separator (which is usually a newline) to the output if it doesn't have one at the end. write outputs only what it is given.

Pesto
+5  A: 

In cases like this, I always start with the Ruby Core documentation, in this case the IO class.

ios.puts(obj, ...) => nil

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

ios.write(string) => integer

Writes the given string to ios. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written.

Michael Sepcot
+2  A: 

What's the difference between print and write then?

kyku
#print is similar to #puts, in that it outputs a record separator. The differences are that #print calls to_s on anything other than Strings (try print [1, 2, 3] vs. puts [1, 2, 3]) and what happens if they're called without an argument (print outputs $_, puts outputs the record separator).
Pesto