Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Ruby's puts and write methods?

Tags:

What's the difference between...

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

...and...

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

...?

like image 345
Ethan Avatar asked Mar 04 '09 20:03

Ethan


People also ask

Whats the difference between puts and print in Ruby?

puts and print The puts (short for "out*put s*tring") and print commands are both used to display in the console the results of evaluating Ruby code. The primary difference between them is that puts adds a new line after executing, and print does not.

What is the difference between puts and return in Ruby?

puts(string) in ruby writes the string value into $stdout . For example if you run ruby console in terminal, string will be written into your terminal. At the same time every method in ruby returns something and method puts returns nil .

What's the difference between puts and print?

Hi, The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.

What does print mean in Ruby?

When you want to print something on the screen for the user to see, you normally use puts . Like this: puts "Hello there!" Puts automatically adds a new line at the end of your message every time you use it. If you don't want a newline, then use print .


2 Answers

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.

like image 121
Pesto Avatar answered Sep 20 '22 04:09

Pesto


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.

like image 25
Michael Sepcot Avatar answered Sep 22 '22 04:09

Michael Sepcot