Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

io

ruby

console

People also ask

How do you print without newline in Ruby?

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 .

Which command is used to add a newline to the end of the output in Ruby?

"\n" is newline, '\n\ is literally backslash and n.

What does puts do in Rails?

The puts method is for printing a string to the console. If you wanted to set each of the values of the array to a certain value in order to print it out later, you should use #map .

How do you print on the same line in Ruby?

We can also use "\n" ( newline character ) to print a new line whenever we want as used in most of the programming languages.


You need to use print instead of puts. Also, if you want the dots to appear smoothly, you need to flush the stdout buffer after each print...

def print_and_flush(str)
  print str
  $stdout.flush
end

100.times do
  print_and_flush "."
  sleep 1
end

Edit: I was just looking into the reasoning behind flush to answer @rubyprince's comment, and realised this could be cleaned up a little by simply using $stdout.sync = true...

$stdout.sync = true

100.times do
  print "."
  sleep 1
end