Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我是红宝石初学者。我有以下代码询问用户他的姓名并将其打印回来。
print 'Enter your name : ' name = gets() print("Hey,#{name} !")
如果我输入 John Doe 作为名称,输出如下
Hey,John Doe !
printlikeputs不会在输出后自动换行,但我注意到在上述情况下,我输入的任何内容#{name}都打印在新行上。为什么会这样?
print
puts
#{name}
gets()正在返回由您按回车键引起的换行符。试着把name = gets().chomp它剪掉。
gets()
name = gets().chomp
如果您在 OS X 上并在 irb 中运行它,您也可以输入“John Doe”,然后按 control+d 两次。
我认为windows的等价物是control+z。
另外,如果你这样做了print name.inspect,那么你肯定会发现它name包含一个换行符 - 它会打印出来"John Doe\n"。
print name.inspect
name
"John Doe\n"