What's the difference between...
File.open('abc', 'w') { |f| f.puts 'abcde' }
...and...
File.open('abc', 'w') { |f| f.write 'abcde' }
...?
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.
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 .
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With