How to print something without a new line in ruby - ruby

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

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

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

$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?"

Related

Add line break/new line in IRB?

How do I add a line-break/new-line in IRB/Ruby? The book I'm learning from shows this code:
print "2+3 is equal to "
print 2 + 3
without telling how to go to the second line without hitting Enter, which obviously just runs the program.
You could use semicolon at the end of statement like this puts "hello";puts"world"
That book might be taking very tiny steps to introducing this idea:
print "Continues..."
puts "(Up to here)"
The print function just outputs to the terminal exactly what it's given. The puts function does the same but also adds a newline, which is what you want.
The more Ruby way of doing this is either:
puts "2+3 equals #{2+3}" # Using string interpolation
puts "2+3 equals %d" % (2 + 3) # Using sprintf-style interpolation
Now if you're using irb, that's a Read-Evaluate-Print-Loop (REPL) which means it executes everything you type in as soon as you press enter, by design. If you want to use your original code, you need to force it on one line:
print "2+3 equals "; print 2+3
Then that will work as expected. The ; line separator is rarely used in Ruby, most style guides encourage you to split things up onto multiple lines, but if you do need to do a one-liner, this is how.
When writing code in, say a .rb file the return key is just used for formatting and doesn't execute any code.
You can put a semicolon after the first line, like this:
print "2+3 is equal to ";
print 2 + 3

Ruby : get output of external command even when there is no line break

I try to run an external command in Ruby, and parse its output .
IO.popen(command, :err=>[:child, :out]) {|ls_io|
ls_io.each do |line|
print line
end
}
This way of doing it works wonders… except when I parse the progress-output of a c-program that shows it progress to stdout with \r.
As long as the c-program has not outputted a \n (that is as long as it has not finished some long-operation), Ruby waits and sees nothing. Then when a \n is outputted, Ruby sees it all
1%\r2%\r3%\r…100%
task finished
I tried all of the many ways to call external commands (eg Calling shell commands from Ruby) ; but none seem to capture the progress. I also tried every opeartor such as STDOUT.sync = true, and the c-program does call fflush(stdout)
I finally found a workaroud. I do :
IO.popen(commande, :err=>[:child, :out]) {|ls_io|
while true
byte=ls_io.read(1)
if byte.nil?
break
end
print byte
end
}
It's stupid… but it works.
Any more elegant way, and much more efficient way to do this ? Performance is terrible, as if the "refresh rate" was slow.
Set the input record separator to "\r" right before your block (provided you know it in advance):
$/ = "\r"
Reference of global preset variables: http://www.zenspider.com/Languages/Ruby/QuickRef.html#pre-defined-variables

One liner in Ruby for displaying a prompt, getting input, and assigning to a variable?

Often I find myself doing the following:
print "Input text: "
input = gets.strip
Is there a graceful way to do this in one line? Something like:
puts "Input text: #{input = gets.strip}"
The problem with this is that it waits for the input before displaying the prompt. Any ideas?
I think going with something like what Marc-Andre suggested is going to be the way to go, but why bring in a whole ton of code when you can just define a two line function at the top of whatever script you're going to use:
def prompt(*args)
print(*args)
gets
end
name = prompt "Input name: "
Check out highline:
require "highline/import"
input = ask "Input text: "
One liner hack sure. Graceful...well not exactly.
input = [(print 'Name: '), gets.rstrip][1]
I know this question is old, but I though I'd show what I use as my standard method for getting input.
require 'readline'
def input(prompt="", newline=false)
prompt += "\n" if newline
Readline.readline(prompt, true).squeeze(" ").strip
end
This is really nice because if the user adds weird spaces at the end or in the beginning, it'll remove those, and it keeps a history of what they entered in the past (Change the true to false to not have it do that.). And, if ARGV is not empty, then gets will try to read from a file in ARGV, instead of getting input. Plus, Readline is part of the Ruby standard library so you don't have to install any gems. Also, you can't move your cursor when using gets, but you can with Readline.
And, I know the method isn't one line, but it is when you call it
name = input "What is your name? "
Following #Bryn's lead:
def prompt(default, *args)
print(*args)
result = gets.strip
return result.empty? ? default : result
end
The problem with your proposed solution is that the string to be printed can't be built until the input is read, stripped, and assigned. You could separate each line with a semicolon:
$ ruby -e 'print "Input text: "; input=gets.strip; puts input'
Input text: foo
foo
I found the Inquirer gem by chance and I really like it, I find it way more neat and easy to use than Highline, though it lacks of input validation by its own.
Your example can be written like this
require 'inquirer'
inputs = Ask.input 'Input text'

Ruby and Netbeans problem

I'm reading a file line by line in a simple program and when I print the the lines to the screen the last line can't be seen at the ouput window in Netbeans 6.5.1 IDE on Windows XP but when I run the program directly from the command line as "ruby main.rb" there is not a problem (i.e the last line can be seen).I'm using Ruby 1.8.6.Here is the entire code :
File.open("songs.txt","r") do |file|
file.each do |line|
print line
end
end
This will work better if you use puts which will append a newline terminator if there is not already one at the end of the line, forcing a buffer flush.
I've never run across this before myself, but my guess would be that your final line doesn't have a trailing line break, so the Netbeans console isn't flushing the line. Try adding $stdout.flush at the end of the program and see what happens.
By the way, you can simplify this code slightly by rewriting it using foreach:
File.foreach("songs.txt","r") do |file|
print line
end

How to add extra newline with 'puts' without sticking newline character into string?

If I say
puts "Hello"
and decide to add an extra newline I need to do this:
puts "Hello\n"
Having this character in the string is ugly. Is there any way to do this without polluting my string?
Just make another call to puts:
puts "Hello"
puts
puts "Hello",""
I often find myself adding a constant in ruby to contain these characters
NEW_LINE = "\n"
puts "Hello" + NEW_LINE
I think it is more readable and makes a change to all newline characters easy if anyone ever decides to separate each line by something else at some later date.
Do you think this looks nicer?
puts "Hello"+$/
</evil>
The reason Ruby uses "\n" for a newline is because its based on C. Ruby MRI is written in C and even JRuby is written in Java which is based on C++ which is based on C... you get the idea! So all these C-style languages use the "\n" for the new line.
You can always write your own method that acts like puts but adds new lines based upon a parameter to the method.
you can just write
p "Hello"
p
That should work as well if you want to keep it short and simple
Well, I don't think an explicit newline is ugly. mipadi's answer is just fine as well. Just to throw another answer in, make an array of the lines then join the aray with a newline. :)
What you want fixed:
input for script:
puts "Hello there"
puts "Goodbye"
Output from script:
Hello thereGoodbye
Fix for the problem:
Input for script:
puts "Hello there"
puts
puts "Goodbye"
Output from script:
Hello there
Goodbye

Resources