print function in ruby [duplicate]
Asked Answered
O

2

1

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 ?

Ocd answered 11/12, 2010 at 8:6 Comment(2)
hint: name contains a character you typed in (pressed a key for) but are not expecting.Adenoidectomy
Oh yeah, the newline character ! :D...thank you ! :)Ocd
Z
5

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

Zippora answered 11/12, 2010 at 8:9 Comment(0)
C
1

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".

Chanel answered 11/12, 2010 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.