Milksnake12
Milksnake12

Reputation: 561

Ruby Multi-Line Input for Only One Input

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?

Upvotes: 4

Views: 3517

Answers (3)

Oliver Gaida
Oliver Gaida

Reputation: 1920

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

Upvotes: 0

Anthony
Anthony

Reputation: 15967

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

Upvotes: 9

daremkd
daremkd

Reputation: 8424

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"

Upvotes: 2

Related Questions