问题
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