116

puts statement in ruby automatically adds a new line, how do I avoid it?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
priya
  • 24,861
  • 26
  • 62
  • 81
  • Possible duplicate of [How can I use "puts" to the console without a line break in ruby on rails?](https://stackoverflow.com/questions/5080644/how-can-i-use-puts-to-the-console-without-a-line-break-in-ruby-on-rails) – ymoreau Aug 17 '18 at 08:31
  • `puts` puts an EOL, `print` doesn't. `p` does something else! – not2qubit Jan 25 '22 at 22:12

3 Answers3

148

Use print instead. You may want to follow it up by STDOUT.flush.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
8

Also, you'll need to append "\r" at end of line to indicate "carriage return" and do next print at beginning of current line

  • 3
    Not if he's simply planning to print more at the end of the current line. He can use puts for the last print to complete the line. This is useful when printing a list of varying (yet short) length, for example. – BobDoolittle Sep 22 '15 at 00:06
6
$stdout.sync = true

100.times do
    print "."
    sleep 1
end

"How can I use “puts” to the console without a line break in ruby on rails?"

Community
  • 1
  • 1
Atika
  • 1,560
  • 18
  • 18