You could let the user end input by hitting Enter on a blank line and leaving the rest of the lines untouched:
puts "Enter the value, then hit ENTER on blank line to finish"
value = ''
until (line = gets).chomp.empty?
value << line
end
value.chomp!
data = { "test" => "data", "value" => value }
puts data
This, after entering foo
Enterbar
EnterEnter will produce:
Enter the value, then hit ENTER on blank line to finish
foo
bar
{"test"=>"data", "value"=>"foo\nbar"}
The only limitation is that you cannot have a newline at the end of the value.
Another possibility is to “unescape” the string after reading it from the input with eval
. Since eval
is potentially insecure, i would rather go with the yaml
library, as suggested in this answer to a related question:
require 'yaml'
puts "Enter the value"
line = gets.chomp
value = YAML.load(%Q(---\n"#{line}"\n))
data = { "test" => "data", "value" => value }
puts data
This, after entering foo\nbar
Enter will produce:
Enter the value
foo\nbar
{"test"=>"data", "value"=>"foo\nbar"}
The plus is that this can handle newlines at arbitrary positions.