print function in ruby [duplicate]

无人久伴 提交于 2019-12-13 02:38:21

问题


I'm a ruby beginner. I have the following code which asks the user for his name and prints it back.

print 'Enter your name : '
name = gets()
print("Hey,#{name} !")

If I enter John Doe as the name, the output is as follows

Hey,John Doe
!

print unlike puts does not automatically put a new line after output but I've noticed that in the above case anything I enter after #{name} is printed on a new line. Why is this so ?


回答1:


gets() is returning the newline caused by you pressing the enter key. Try name = gets().chomp to trim it off.




回答2:


If you're on OS X, and running this in irb, you could also type in "John Doe" and then press control+d twice.

I think the equivalent for windows is control+z.

Also, if you did print name.inspect, then you'd find out for sure that name contains a newline - it'd print out "John Doe\n".



来源:https://stackoverflow.com/questions/4415834/print-function-in-ruby

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