问题
I wrote this:
print "Enter your name:"
name = gets
puts "Hello #{name}. Please to meet you."
and the result was like this:
Hello Moemen
. Pleased to meet you
Why is the remainder of the string after the variable continued in another line? I want it to be
"Hello Moemen. Pleased to meet you."
Am I missing something?I'm using sublime text 2, and I couldn't get the
gets
method to let me input data; it just prints the outcome in the console without giving me a chance to input anything. Any idea?
回答1:
When you use gets
, the input is going to be followed by a newline so you will need to strip the newline before printing it out.
print "Enter your name:"
name = gets.chomp
puts "Hello #{name}. Pleased to meet you."
That should solve your problem.
回答2:
What you report would not happen. It cannot be true. When you get a string by gets
, you may get a string like "Moemen\n"
. Since an input is delimited by "\n"
, the string has that at the end. When it is interpolated into "Hello #{name}. Please to meet you."
, you would get:
Hello Moemen
. Please to meet you.
but not
Hello Moemen
. Pleased to meet you
as you report. That does not happen.
In order to get "Hello Moemen. Pleased to meet you."
, you need to change the string to "Hello #{name.chomp}. Pleased to meet you."
.
来源:https://stackoverflow.com/questions/17668971/ruby-gets-adds-newline-character