Ruby — 'gets' adds newline character [closed]

别说谁变了你拦得住时间么 提交于 2019-12-08 15:32:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!