-1

I'm trying construct a hash in ruby from the input provided by user.But when i give an string input with "\n",it is automatically replaced by double slash followed by n(\ \n) in the hash.But i want the data to be as it is in the hash.Below is my code.

puts "Enter the value" 

value = gets.chomp 

data = { "test" => "data", "value" => value }

puts data
NagaLakshmi
  • 715
  • 3
  • 12
  • 24

2 Answers2

2

This has nothing to do with the hash. You simply can't input \n as a control character (at least not using gets).

If, as a user, you type \n, you have typed a literal backslash, followed by a literal n. That's represented as "\\n" in a string.

The only control character I can think of right now that you can input directly is the tab character \t (and you get that by typing an actual tab, not \t:

irb(main):001:0> gets.chomp
\n
=> "\\n"
irb(main):002:0> gets.chomp
a       b
=> "a\tb"
irb(main):003:0> gets.chomp

=> ""
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

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 fooEnterbarEnterEnter 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\nbarEnter will produce:

Enter the value
foo\nbar

{"test"=>"data", "value"=>"foo\nbar"}

The plus is that this can handle newlines at arbitrary positions.

Community
  • 1
  • 1
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168