Ruby: Why is this printed on a new line?
It is printed on the next line because you press ENTER to finish inputing your data (and therefore you make a new line). Didn't it confuse you that second print
also goes to a new line?
Adding double quotes around a string adds the closing quote on a new line
This doesn't have to do with the quotations you're adding, but rather that you're not using String#chomp to remove the trailing newline that is included with every gets
:
gets # I type foo
# => "foo\n"
gets.chomp # I type foo
# => "foo"
You don't actually need the to_s
here because gets
will always return a string.
ruby How I could print without leave newline space for each line?
You have two solutions.
The first one uses puts
as you currently do:
File.open('yourfile.txt', 'a+') { |f|
f.puts "#{parts[0]}#{parts[1]}#{parts[2]}#{input3}"
}
The second one uses write
instead of puts
:
File.open('yourfile.txt', 'a+') { |f|
f.write parts[0]
f.write parts[1]
f.write parts[2]
f.write input3
}
gets.chomp without moving to a new line
You can do this by using the (very poorly documented) getch
:
require 'io/console'
require 'io/wait'
loop do
chars = STDIN.getch
chars << STDIN.getch while STDIN.ready? # Process multi-char paste
break if ["\r", "\n", "\r\n"].include?(chars)
STDOUT.print chars
end
References:
- http://ruby-doc.org/stdlib-2.1.0/libdoc/io/console/rdoc/IO.html#method-i-getch
- http://ruby-doc.org/stdlib-2.1.0/libdoc/io/wait/rdoc/IO.html#method-i-ready-3F
Related follow-up question:
enter & IOError: byte oriented read for character buffered IO
Ruby- gets issue
You can write your own Python equivalent input
method:
def input(prompt)
print(prompt) # Output prompt
$stdout.flush # Flush stdout buffers to ensure prompt appears
gets.chomp # Get user input, remove final newline with chomp
end
Now we can try it:
name = input('What is your name? ')
puts "Welcome #{name}"
For more information on the methods used here. See these:
IO.flush
String.chomp
Related Topics
Need to Split Arrays to Sub Arrays of Specified Size in Ruby
Execute Bash Commands from a Rakefile
How to Install Rvm on Windows 7
How to Access a Variable Defined in a Ruby File I Required in Irb
Mavericks, Rbenv, Your Ruby Version Is 2.0.0, But Your Gemfile Specified 2.1.1
Rubyinstaller 2.2.1 and Rails - Rake Cannot Load Nokogiri
Ruby Array Subtraction Without Removing Items More Than Once
What's the 'Ruby Way' to Iterate Over Two Arrays at Once
How to Swap Keys and Values in a Hash
Ruby on Rails - Access Controller Variable from Model
Ruby: Easiest Way to Filter Hash Keys
How to Run Rake Tasks Within a Ruby Script
What Are the Magic $-Prefixed Variables in Ruby
How to Match Something With Regex That Is Not Between Two Special Characters
Using God to Monitor Unicorn - Start Exited with Non-Zero Code = 1
Setting Up Rake-Pipeline for Use with Handlebars Alongside Google App Engine