4

I have a small program that I'm working on that at one point I would like the user to be able to input a potentially multiline response.

I've found the example with

$/ = "END"
user_input = STDIN.gets
puts user_input

But this makes all inputs require the END keyword, which I would only need for the one input.

How can I produce a multi-line input for just the one input?

2
  • 2
    The user obviously needs a way to tell you when he or she is finished. That might be an escape key, for example, or two returns in a row. You might consider using IO#getc for input. Commented Feb 10, 2015 at 22:22
  • The easiest way to signal "I'm finished" is with Ctrl-D. See my answer below. Commented Feb 11, 2015 at 1:24

3 Answers 3

9

IO#gets has an optional parameter that allows you to specify a separator. Here's an example:

puts "Enter Response"
response = gets.chomp

puts "Enter a multi line response ending with a tab"
response = gets("\t\n").chomp

Output:

Enter Response
hello
Enter a multi line response ending with a tab
ok
how
is
this
Sign up to request clarification or add additional context in comments.

3 Comments

Nice one. I didn't know about that. Maybe replace "Gets has..." with IO#gets has...".
Thanks Cary, included the link.
When I used this, it ran right over my next gets. print "Multi-line response: " response = gets("done").chomp print "One line Response: " oneLine = gets.chomp
2

This method accepts text until the first empty line:

def multi_gets(all_text='')
  until (text = gets) == "\n"
    all_text << text
  end
  return all_text.chomp # you can remove the chomp if you'd like
end

puts 'Enter your text:'
p multi_gets

Output:

Enter your text:
abc
def

"abc\ndef"

Comments

0

i use this:

in = STDIN.readline(sep="\t\n")
puts in

ends the input. For more info see https://ruby-doc.org/core-2.2.0/IO.html#method-i-readline

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.