Why Does Ruby'S 'Gets' Includes the Closing Newline

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



Leave a reply



Submit