Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby multiple print on the same line

Tags:

ruby

printing

Is there an easy way for Ruby to print in one line, then for the next print, it prints to the same line from the beginning.

I am trying to make a simple file counter shown on the stdout while files are being generated. It looks like a rapidly updated number at the same position on the screen.

like image 746
ccy Avatar asked Sep 09 '11 18:09

ccy


People also ask

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.

What does P do in Ruby?

As already mentioned, in ruby the method p can come in handy when you are trying to figure out what a certain line of code does, what's assigned to a variable, or what a method call returns. As it tells you exactly what you are looking at.

What is the difference between the puts and print methods?

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.

How do you go to the next line in Ruby?

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


1 Answers

could use \r..

while(true) do
  print "\\\r"
  print "|\r"
  print "/\r"
end

Will print the char and then move the cursor back and print over it, making a little spinner like thing. Else you can look at something like curses.... (https://github.com/rkumar/rbcurse for a ruby wrapper)

like image 90
Doon Avatar answered Oct 11 '22 00:10

Doon