Nathan
Nathan

Reputation: 23

Ruby Console: How to Keep 'gets' from adding a new line when the user inputs

Why does gets always add a new line when the user inputs the number of boxes?

I want the next print statement to be shown on the same line as the input.

    print "Enter the number of boxes: "
    boxes = gets.chomp
    print "Enter number of columns to print the boxes in: "
    columns = gets.chomp

I want output to look like this:

Enter the number of boxes: 47 Enter number of columns to print the boxes in: 4

I don't want to begin a new line until after the second input is received.

Upvotes: 2

Views: 465

Answers (2)

Dave Newton
Dave Newton

Reputation: 160181

You'll need to use IO/console and build up your input a character at a time:

require 'io/console'

def cgets(stream=$stdin)
  $stdin.echo = false
  s = ""
  while true do
    c = stream.getc
    return s if c == "\n"
    s << c
  end
end

The issue is echoing the input back; getting the character out when it isn't a newline is a bit problematic (at least locally, not on my regular machine). Also, since you're getting the characters manually, it removes normal readline functionality, so behavior will be system-dependent e.g., Unixy systems might lose their backspace etc.

That said, yuck; IMO on the console this is an unexpected UI pattern, and keeping the input on two lines is more obvious, and more common.

Upvotes: 1

peter
peter

Reputation: 42182

In windows you can do it like this, otherwise you would need a similar read_char method that works in your OS

def read_char #only on windows
  require "Win32API"
  Win32API.new("crtdll", "_getch", [], "L").Call
end

def get_number
  number, inp = "", 0
  while inp != 13
    inp = read_char
    if "0123456789"[inp.chr]
      number += inp.chr
      print inp.chr  
    end
  end
  number
end

print "Enter the number of boxes: "
boxes = get_number
print " Enter number of columns to print the boxes in: "
columns = get_number
puts ""

puts "boxes: #{boxes}"
puts "columns: #{columns}"

# gives
# Enter the number of boxes: 5 Enter number of columns to print the boxes in: 6
# boxes: 5
# columns: 6

Upvotes: 0

Related Questions