ruby 中的打印函数
我是红宝石初学者。我有以下代码,询问用户的姓名并将其打印回来。
print 'Enter your name : '
name = gets()
print("Hey,#{name} !")
如果我输入 John Doe 作为名称,输出如下
Hey,John Doe
!
print
与 puts
不同,它不会在输出后自动添加新行,但我注意到在上述情况下我在 #{name}
之后输入的任何内容都会打印在新行上。为什么会这样呢?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
gets()
返回因按 Enter 键而导致的换行符。尝试name = gets().chomp
将其修剪掉。gets()
is returning the newline caused by you pressing the enter key. Tryname = gets().chomp
to trim it off.如果您使用的是 OS X,并在 irb 中运行此程序,您还可以输入“John Doe”,然后按 control+d 两次。
我认为 Windows 的等效命令是 control+z。
另外,如果您执行了
print name.inspect
,那么您会确定name
包含换行符 - 它会打印出"John Doe\ n”
。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 thatname
contains a newline - it'd print out"John Doe\n"
.